import { db } from './db.js'

const ddlStatements = [
  `CREATE TABLE IF NOT EXISTS meetings (
    id              BIGSERIAL PRIMARY KEY,
    started_at      TIMESTAMPTZ NOT NULL,
    ended_at        TIMESTAMPTZ,
    title           TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
  );`,
  `CREATE TABLE IF NOT EXISTS utterances (
    id              BIGSERIAL PRIMARY KEY,
    meeting_id      BIGINT NOT NULL REFERENCES meetings(id) ON DELETE CASCADE,
    speaker         TEXT NOT NULL DEFAULT 'unknown',
    text            TEXT NOT NULL,
    ts              TIMESTAMPTZ NOT NULL DEFAULT now()
  );`,
  `CREATE TABLE IF NOT EXISTS answers (
    id              BIGSERIAL PRIMARY KEY,
    meeting_id      BIGINT NOT NULL REFERENCES meetings(id) ON DELETE CASCADE,
    question_text   TEXT NOT NULL,
    suggestions     JSONB NOT NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
  );`,
  `CREATE INDEX IF NOT EXISTS idx_utterances_meeting_id_ts
    ON utterances(meeting_id, ts);`,
  `CREATE INDEX IF NOT EXISTS idx_answers_meeting_id_created_at
    ON answers(meeting_id, created_at);`,
]

export async function runMigrations() {
  for (const stmt of ddlStatements) {
    await db.query(stmt)
  }
}

if (process.argv[1]?.includes('migrate')) {
  runMigrations()
    .then(() => {
      // eslint-disable-next-line no-console
      console.log('Migrations complete.')
      process.exit(0)
    })
    .catch((err) => {
      // eslint-disable-next-line no-console
      console.error('Migration failed:', err)
      process.exit(1)
    })
}
