package infra

import (
	"database/sql"
	"embed"
	"fmt"
	"path/filepath"
)

//go:embed vault_index_migrations/*.sql
var vaultIndexMigrationsFS embed.FS

// VaultIndexOpen opens (or creates) the vault_index.db inside vaultPath.
// It applies all embedded migrations idempotently and returns a ready-to-use
// *sql.DB. The caller is responsible for closing the connection.
//
// The database is opened with WAL mode and foreign keys enabled via SQLiteOpen.
// Migrations are applied from vault_index_migrations/*.sql in lexicographic order.
func VaultIndexOpen(vaultPath string) (*sql.DB, error) {
	dbPath := filepath.Join(vaultPath, "vault_index.db")
	db, err := SQLiteOpen(dbPath, "")
	if err != nil {
		return nil, fmt.Errorf("vault_index_open: %w", err)
	}
	if err := ApplyMigrations(db, vaultIndexMigrationsFS, "vault_index_migrations/*.sql"); err != nil {
		db.Close()
		return nil, fmt.Errorf("vault_index_open: apply migrations: %w", err)
	}
	return db, nil
}
