package database

import (
	"database/sql"
	"log"

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

func Open(path string) *sql.DB {
	db, err := sql.Open("sqlite3", path)
	if err != nil {
		log.Fatal("failed to open database:", err)
	}

	if err := db.Ping(); err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	createTables(db)
	return db
}

func createTables(db *sql.DB) {
	query := `
	CREATE TABLE IF NOT EXISTS listing (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		name TEXT NOT NULL,
		slug TEXT NOT NULL UNIQUE,
		description TEXT,
		repo_url TEXT,
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
		show_timestamps INTEGER DEFAULT 1
	);

	CREATE TABLE IF NOT EXISTS release (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		listing_id INTEGER NOT NULL,
		version TEXT NOT NULL,
		title TEXT,
		changelog TEXT,
		is_latest INTEGER DEFAULT 0,
		published_at DATETIME DEFAULT CURRENT_TIMESTAMP,
		FOREIGN KEY (listing_id) REFERENCES listing(id)
	);

	CREATE TABLE IF NOT EXISTS asset (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		release_id INTEGER NOT NULL,
		filename TEXT NOT NULL,
		filepath TEXT NOT NULL,
		os TEXT,
		arch TEXT,
		size INTEGER,
		sha256 TEXT,
		alt_url TEXT,
		FOREIGN KEY (release_id) REFERENCES release(id)
	);

	CREATE TABLE IF NOT EXISTS page (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		listing_id INTEGER NOT NULL,
		slug TEXT NOT NULL,
		title TEXT NOT NULL,
		body TEXT,
		sort_order INTEGER DEFAULT 0,
		FOREIGN KEY (listing_id) REFERENCES listing(id)
	);

	CREATE TABLE IF NOT EXISTS screenshot (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		listing_id INTEGER NOT NULL,
		filename TEXT NOT NULL,
		caption TEXT,
		sort_order INTEGER DEFAULT 0,
		FOREIGN KEY (listing_id) REFERENCES listing(id)
	);
	`

	_, err := db.Exec(query)
	if err != nil {
		log.Fatal("Failed to create tables:", err)
	}

	log.Println("Database tables ready")
}
