package db

import (
	"database/sql"
	_ "embed"
	"fmt"
	"strings"

	_ "modernc.org/sqlite"
)

//go:embed migrations/000001_init.up.sql
var initMigrationUp string

//go:embed migrations/000001_init.down.sql
var initMigrationDown string

// Connect opens an SQLite database connection with appropriate pragmas
func Connect(dbPath string) (*sql.DB, error) {
	dsn := dbPath
	if !strings.Contains(dsn, "?") {
		dsn += "?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
	}
	db, err := sql.Open("sqlite", dsn)
	if err != nil {
		return nil, fmt.Errorf("failed to open database: %w", err)
	}

	if err := db.Ping(); err != nil {
		return nil, fmt.Errorf("failed to ping database: %w", err)
	}

	return db, nil
}

// RunMigrations applies up migrations
func RunMigrations(db *sql.DB) error {
	if _, err := db.Exec(initMigrationUp); err != nil {
		return fmt.Errorf("failed to apply migration up: %w", err)
	}
	return nil
}

// RollbackMigrations applies down migrations
func RollbackMigrations(db *sql.DB) error {
	if _, err := db.Exec(initMigrationDown); err != nil {
		return fmt.Errorf("failed to apply migration down: %w", err)
	}
	return nil
}
