package store

import (
	"database/sql"
	"fmt"
	"os"
	"path/filepath"

	_ "modernc.org/sqlite"

	"git.cloudinit.dev/coreci/orca/internal/certpaths"
)

func Open(path string) (*sql.DB, error) {
	if path == "" {
		path = certpaths.DBPath()
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return nil, fmt.Errorf("create db dir: %w", err)
	}
	db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)")
	if err != nil {
		return nil, fmt.Errorf("open sqlite: %w", err)
	}
	if err := db.Ping(); err != nil {
		_ = db.Close()
		return nil, fmt.Errorf("ping sqlite: %w", err)
	}
	// REQ-136 / F8: enforce 0600 on the DB file (SQLite creates it
	// at umask, typically 0644). We chmod after open+ping (the file
	// exists at this point). Non-fatal if chmod fails (e.g. the DB
	// is at a path we don't own); the caller is warned via vet.
	if err := os.Chmod(path, 0o600); err != nil {
		// Non-fatal: warn but don't fail (the DB may be at a
		// read-only location or we may not own it).
		_ = err
	}
	if err := migrate(db); err != nil {
		_ = db.Close()
		return nil, fmt.Errorf("migrate: %w", err)
	}
	return db, nil
}
