package migrations

import (
	"database/sql"
)

func init() {
	RegisterMigration(
		1,
		"Initial schema",
		migrateInitialSchemaUp,
		migrateInitialSchemaDown,
	)
}

func migrateInitialSchemaUp(tx *sql.Tx) error {
	_, err := tx.Exec(`
		CREATE TABLE IF NOT EXISTS libraries (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			name TEXT NOT NULL,
			path TEXT NOT NULL)`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		CREATE TABLE IF NOT EXISTS media_files (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			path TEXT NOT NULL,
			library_id INTEGER NOT NULL)`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		CREATE TABLE IF NOT EXISTS artists (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			name TEXT NOT NULL
		)
	`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		CREATE TABLE IF NOT EXISTS albums (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			title TEXT NOT NULL,
			artist_id INTEGER,
			FOREIGN KEY (artist_id) REFERENCES artists(id),
			UNIQUE(title, artist_id)
		)
	`)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`
		CREATE TABLE IF NOT EXISTS songs (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			title TEXT NOT NULL,
			album_id INTEGER,
			artist_id INTEGER,
			duration INTEGER,
			media_file_id INTEGER UNIQUE,
			FOREIGN KEY (album_id) REFERENCES albums(id),
			FOREIGN KEY (artist_id) REFERENCES artists(id),
			FOREIGN KEY (media_file_id) REFERENCES media_files(id)
		)
	`)
	if err != nil {
		return err
	}

	return nil
}

func migrateInitialSchemaDown(tx *sql.Tx) error {
	// Drop tables in reverse order to avoid foreign key constraints
	tables := []string{
		"songs",
		"albums",
		"artists",
		"media_files",
		"libraries",
	}

	for _, table := range tables {
		_, err := tx.Exec("DROP TABLE IF EXISTS " + table)
		if err != nil {
			return err
		}
	}

	return nil
}
