/**
 * 迁移脚本：为 admin_api_token 表创建数据库结构
 * 运行方式: bun --env-file=.env.local src/lib/db/migrate-api-token.ts
 */
import { pool } from "../db";

async function migrate() {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // 检查表是否存在
    const tableCheck = await client.query(`
      SELECT 1 FROM information_schema.tables
      WHERE table_schema = 'public' AND table_name = 'admin_api_token'
    `);

    if (!tableCheck.rows.length) {
      await client.query(`
        CREATE TABLE admin_api_token (
          id           SERIAL PRIMARY KEY,
          name         VARCHAR(255) NOT NULL,
          token_hash   VARCHAR(64) NOT NULL UNIQUE,
          token_prefix VARCHAR(32) NOT NULL,
          permissions  TEXT[]     NOT NULL DEFAULT '{}',
          created_by   INTEGER    NOT NULL REFERENCES admin_user(id) ON DELETE SET NULL,
          created_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
          last_used_at TIMESTAMPTZ,
          expires_at   TIMESTAMPTZ,
          is_active    BOOLEAN     NOT NULL DEFAULT true
        )
      `);
      await client.query(`
        CREATE INDEX idx_admin_api_token_hash ON admin_api_token(token_hash)
      `);
      await client.query(`
        COMMENT ON TABLE admin_api_token IS 'Admin API Token for programmatic access'
      `);
      console.log("Created table: admin_api_token");
    } else {
      console.log("Table admin_api_token already exists, skipping.");
    }

    await client.query("COMMIT");
    console.log("Migration completed successfully.");
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Migration failed:", e);
    throw e;
  } finally {
    client.release();
    await pool.end();
  }
}

migrate().catch((e) => { console.error(e); process.exit(1); });
