package db

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"log"
	"path/filepath"

	_ "github.com/mattn/go-sqlite3"
)

func Migrate(db *sql.DB) error {
	migrationDir := "./migrations"
	
	files, err := ioutil.ReadDir(migrationDir)
	if err != nil {
		return fmt.Errorf("failed to read migration directory: %w", err)
	}

	for _, file := range files {
		if filepath.Ext(file.Name()) != ".sql" {
			continue
		}

		migrationPath := filepath.Join(migrationDir, file.Name())
		log.Printf("Running migration: %s", file.Name())

		if err := runMigration(db, migrationPath); err != nil {
			return fmt.Errorf("failed to run migration %s: %w", file.Name(), err)
		}
	}

	return nil
}

func runMigration(db *sql.DB, path string) error {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	_, err = db.Exec(string(content))
	return err
}
