import type { AppDatabase } from "./database.js";

export function migrate(db: AppDatabase): void {
  db.exec(`
    CREATE TABLE IF NOT EXISTS chat_sessions (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      title TEXT,
      system_prompt TEXT,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL
    );

    CREATE INDEX IF NOT EXISTS idx_chat_sessions_user_updated
      ON chat_sessions(user_id, updated_at DESC);

    CREATE TABLE IF NOT EXISTS chat_messages (
      id TEXT PRIMARY KEY,
      session_id TEXT NOT NULL,
      user_id TEXT NOT NULL,
      role TEXT NOT NULL,
      content TEXT NOT NULL,
      metadata TEXT,
      created_at TEXT NOT NULL,
      FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
    );

    CREATE INDEX IF NOT EXISTS idx_chat_messages_session_user_created
      ON chat_messages(session_id, user_id, created_at ASC);

    CREATE TABLE IF NOT EXISTS webhook_runs (
      id TEXT PRIMARY KEY,
      webhook_id TEXT NOT NULL,
      user_id TEXT NOT NULL,
      session_id TEXT NOT NULL,
      status TEXT NOT NULL,
      request_payload TEXT,
      response_status INTEGER,
      attempts INTEGER NOT NULL DEFAULT 1,
      created_at TEXT NOT NULL,
      FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE
    );

    CREATE INDEX IF NOT EXISTS idx_webhook_runs_session_user_created
      ON webhook_runs(session_id, user_id, created_at DESC);
  `);

  // Idempotent additive migrations for existing DBs.
  const webhookRunColumns = db
    .prepare("PRAGMA table_info(webhook_runs)")
    .all() as Array<{ name: string }>;
  if (!webhookRunColumns.some((column) => column.name === "attempts")) {
    db.exec("ALTER TABLE webhook_runs ADD COLUMN attempts INTEGER NOT NULL DEFAULT 1");
  }

  const sessionColumns = db
    .prepare("PRAGMA table_info(chat_sessions)")
    .all() as Array<{ name: string }>;
  if (!sessionColumns.some((column) => column.name === "system_prompt")) {
    db.exec("ALTER TABLE chat_sessions ADD COLUMN system_prompt TEXT");
  }
}
