import type { Kysely } from "kysely";
import { sql } from "kysely";
import type { DB } from "../db";

export async function up(db: Kysely<DB>): Promise<void> {
  await db.schema
    .createTable("admin_activity_log")
    .ifNotExists()
    .addColumn("id", "uuid", (col) =>
      col.primaryKey().defaultTo(sql`gen_random_uuid()`),
    )
    .addColumn("admin_email", "text", (col) => col.notNull())
    .addColumn("action", "text", (col) => col.notNull()) // e.g., "GET /admin/users", "POST /admin/bookings"
    .addColumn("method", "text", (col) => col.notNull())
    .addColumn("url", "text", (col) => col.notNull())
    .addColumn("status_code", "integer")
    .addColumn("payload", "jsonb")
    .addColumn("ip_address", "text")
    .addColumn("user_agent", "text")
    .addColumn("performed_at", "timestamptz", (col) =>
      col.notNull().defaultTo(sql`NOW()`),
    )
    .execute();

  await db.schema
    .createIndex("admin_activity_log_email_time_idx")
    .ifNotExists()
    .on("admin_activity_log")
    .columns(["admin_email", "performed_at"])
    .execute();
}

export async function down(db: Kysely<DB>): Promise<void> {
  await db.schema.dropTable("admin_activity_log").ifExists().execute();
}
