package db

import (
	"context"
	"database/sql"
	"embed"
	"fmt"
	"sort"
)

//go:embed schema/*.sql
var schemaFS embed.FS

func ApplyMigrations(ctx context.Context, db *sql.DB) error {
	files, err := schemaFS.ReadDir("schema")
	if err != nil {
		return fmt.Errorf("read embedded schema directory: %w", err)
	}

	names := make([]string, 0, len(files))
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		names = append(names, file.Name())
	}
	sort.Strings(names)

	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin schema transaction: %w", err)
	}
	defer tx.Rollback()

	for _, name := range names {
		content, err := schemaFS.ReadFile("schema/" + name)
		if err != nil {
			return fmt.Errorf("read embedded schema file %q: %w", name, err)
		}
		if _, err := tx.ExecContext(ctx, string(content)); err != nil {
			return fmt.Errorf("apply schema file %q: %w", name, err)
		}
	}

	if err := tx.Commit(); err != nil {
		return fmt.Errorf("commit schema transaction: %w", err)
	}

	return nil
}
