/**
 * Migration: workspace_alert_config
 * 告警配置表（workspace 级别的阈值告警）
 */
import { query } from "../db";

export async function migrate() {
  // Check if table exists
  const { rows } = await query<{ exists: boolean }>(
    `SELECT EXISTS (
       SELECT FROM information_schema.tables
       WHERE table_schema = 'public' AND table_name = 'workspace_alert_config'
     ) AS exists`
  );
  if (rows[0]?.exists) {
    console.log("Table workspace_alert_config already exists, skipping.");
    return;
  }

  await query(`
    CREATE TABLE workspace_alert_config (
      id SERIAL PRIMARY KEY,
      workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
      alert_type VARCHAR(32) NOT NULL,          -- 'low_balance' | 'monthly_quota' | 'usage_surge'
      threshold DECIMAL(10, 4) NOT NULL,       -- 触发阈值（如 10.00 表示余额低于 $10）
      email_enabled BOOLEAN DEFAULT true,
      enabled BOOLEAN DEFAULT true,
      created_by INTEGER REFERENCES admin_user(id),
      created_at TIMESTAMPTZ DEFAULT NOW(),
      updated_at TIMESTAMPTZ DEFAULT NOW(),
      UNIQUE(workspace_id, alert_type)
    )
  `);
  await query(`CREATE INDEX idx_alert_config_workspace ON workspace_alert_config(workspace_id)`);

  console.log("Created table: workspace_alert_config");
}
