package migrations

import (
	"context"

	"git.haelnorr.com/h/oslstats/internal/db"
	"github.com/uptrace/bun"
)

func init() {
	Migrations.MustRegister(
		// UP: Create initial tables (users, discord_tokens)
		func(ctx context.Context, dbConn *bun.DB) error {
			// Create users table
			_, err := dbConn.NewCreateTable().
				Model((*db.User)(nil)).
				Exec(ctx)
			if err != nil {
				return err
			}

			// Create discord_tokens table
			_, err = dbConn.NewCreateTable().
				Model((*db.DiscordToken)(nil)).
				Exec(ctx)
			return err
		},
		// DOWN: Drop tables in reverse order
		func(ctx context.Context, dbConn *bun.DB) error {
			// Drop discord_tokens first (has foreign key to users)
			_, err := dbConn.NewDropTable().
				Model((*db.DiscordToken)(nil)).
				IfExists().
				Exec(ctx)
			if err != nil {
				return err
			}

			// Drop users table
			_, err = dbConn.NewDropTable().
				Model((*db.User)(nil)).
				IfExists().
				Exec(ctx)
			return err
		},
	)
}
