import { Kysely, sql } from "kysely";

export async function up(db: Kysely<any>): Promise<void> {
  await db.schema
    .createTable("Webhook")
    .addColumn("id", "uuid", (col) =>
      col.primaryKey().defaultTo(sql`gen_random_uuid()`),
    )
    .addColumn("name", "text", (col) => col.notNull())
    .addColumn("description", "text")
    .addColumn("backend_type", "text", (col) => col.notNull())
    .addColumn("backend_id", "uuid", (col) => col.notNull())
    .addColumn("endpoint_url", "text", (col) =>
      col.notNull().check(sql`endpoint_url ~ '^https?://[^/]+'`),
    )
    .addColumn("http_method", "text", (col) =>
      col
        .notNull()
        .defaultTo("post")
        .check(sql`http_method in ('post', 'put')`),
    )
    .addColumn("headers", "jsonb")
    .addColumn("created_at", "timestamptz", (col) =>
      col.notNull().defaultTo(sql`now()`),
    )
    .addColumn("updated_at", "timestamptz", (col) =>
      col.notNull().defaultTo(sql`now()`),
    )
    .execute();

  await db.schema
    .createIndex("WebhookBackendTypeBackendId")
    .on("Webhook")
    .column("backend_type")
    .column("backend_id")
    .execute();
}

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