import { Kysely, sql } from 'kysely';
import bcrypt from 'bcryptjs';

// `any` is required here since migrations should be frozen in time. alternatively, keep a "snapshot" db interface.
export async function up(db: Kysely<any>): Promise<void> {
  await db.schema
    .createTable('admins')
    .addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
    .addColumn('email', 'varchar(255)', (col) => col.notNull().unique())
    .addColumn('display_name', 'varchar(255)', (col) => col.notNull())
    .addColumn('password_hash', 'varchar(255)', (col) => col.notNull())
    .addColumn('role', 'varchar(20)', (col) => col.defaultTo('admin').notNull())
    .addColumn('is_active', 'boolean', (col) => col.defaultTo(true).notNull())
    .addColumn('created_by', 'uuid')
    .addColumn('last_login_at', 'timestamptz')
    .addColumn('created_at', 'timestamptz', (col) => col.defaultTo(sql`now()`).notNull())
    .addColumn('updated_at', 'timestamptz', (col) => col.defaultTo(sql`now()`).notNull())
    .addColumn('deleted_at', 'timestamptz')
    .execute();

  // Seed a bootstrap super admin. Change this password immediately after first login.
  const passwordHash = bcrypt.hashSync('Admin@123!', 10);
  await db
    .insertInto('admins')
    .values({
      email: 'admin@furfinder.com',
      display_name: 'Super Admin',
      password_hash: passwordHash,
      role: 'super_admin',
    })
    .execute();
}

// `any` is required here since migrations should be frozen in time. alternatively, keep a "snapshot" db interface.
export async function down(db: Kysely<any>): Promise<void> {
  await db.schema.dropTable('admins').execute();
}
