import { Kysely, sql } from "kysely";

export async function up(db: Kysely<any>): Promise<void> {
  await db.schema
    .createTable("VoiceProvider")
    .addColumn("id", "uuid", (col) =>
      col.primaryKey().defaultTo(sql`gen_random_uuid()`),
    )
    .addColumn("kind", "text", (col) => col.notNull())
    .addColumn("name", "text", (col) => col.notNull())
    .addColumn("description", "text")
    .addColumn("credentials", "jsonb", (col) => col.notNull())
    .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("VoiceProviderName")
    .on("VoiceProvider")
    .column("name")
    .execute();

  await db.schema
    .createTable("VoiceLine")
    .addColumn("id", "uuid", (col) =>
      col.primaryKey().defaultTo(sql`gen_random_uuid()`),
    )
    .addColumn("provider_id", "uuid", (col) =>
      col.notNull().references("VoiceProvider.id").onDelete("cascade"),
    )
    .addColumn("provider_line_sid", "text", (col) => col.notNull())
    .addColumn("number", "text", (col) => col.notNull())
    .addColumn("name", "text", (col) => col.notNull())
    .addColumn("description", "text")
    .addColumn("language", "text", (col) => col.notNull())
    .addColumn("voice", "text", (col) => col.notNull())
    .addColumn("prompt_text", "text")
    .addColumn("prompt_audio", "jsonb")
    .addColumn("audio_prompt_enabled", "boolean", (col) =>
      col.notNull().defaultTo(false),
    )
    .addColumn("audio_converted_at", "timestamptz")
    .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("VoiceLineProviderId")
    .on("VoiceLine")
    .column("provider_id")
    .execute();

  await db.schema
    .createIndex("VoiceLineProviderLineSid")
    .on("VoiceLine")
    .column("provider_line_sid")
    .execute();

  await db.schema
    .createIndex("VoiceLineNumber")
    .on("VoiceLine")
    .column("number")
    .execute();
}

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