package tables

import (
	"database/sql"

	"code.justin.tv/d8a/iceman/lib/queries"
)

const currentVersion = 2

func VerifyIcemanTables(db *sql.DB, queries queries.DriverQueries) error {
	version, err := getDataVersion(db, queries)
	if err != nil {
		return err
	}

	err = verifyMigrationTable(version, db, queries)
	if err != nil {
		return err
	}

	err = verifyBulkTable(version, db, queries)
	if err != nil {
		return err
	}

	if version < currentVersion {
		if _, err := db.Exec(queries.InsertVersion(), currentVersion); err != nil {
			return err
		}
	}

	return nil
}

func getDataVersion(db *sql.DB, queries queries.DriverQueries) (int, error) {
	row := db.QueryRow(queries.GetDataVersion())

	var version int
	err := row.Scan(&version)
	if err != nil {
		if IsMissingTableError(err) {
			if _, err := db.Exec(queries.CreateVersionsTable()); err != nil {
				return 0, err
			}

			return 0, nil
		}
		return 0, err
	}

	return version, nil
}

func verifyMigrationTable(version int, db *sql.DB, queries queries.DriverQueries) error {
	if version < 1 {
		if _, err := db.Exec(queries.CreateMigrationsTable()); err != nil {
			return err
		}
	}

	return nil
}

func verifyBulkTable(version int, db *sql.DB, queries queries.DriverQueries) error {
	if version < 1 {
		if _, err := db.Exec(queries.CreateBulkTable()); err != nil {
			return err
		}
	}

	if version < 2 {
		if _, err := db.Exec(queries.BulkTableV2()); err != nil {
			return err
		}
	}

	return nil
}
