import { NextRequest, NextResponse } from "next/server";
import { query, getClient } from "@/lib/db";
import { getAdminUserId } from "@/lib/auth";

export const runtime = "nodejs";

interface AlertConfig {
  id: number;
  workspace_id: string;
  alert_type: string;
  threshold: string;
  email_enabled: boolean;
  enabled: boolean;
  created_at: Date;
}

const ALERT_TYPE_LABELS: Record<string, string> = {
  low_balance: "余额不足",
  monthly_quota: "月度配额",
  usage_surge: "使用量激增",
};

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const result = await query<AlertConfig>(
      `SELECT id, workspace_id, alert_type, threshold, email_enabled, enabled, created_at
       FROM workspace_alert_config
       WHERE workspace_id = $1
       ORDER BY alert_type ASC`,
      [id]
    );
    return NextResponse.json({ configs: result.rows });
  } catch (e) {
    console.error("Alert config error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminUserId = getAdminUserId(req);
    if (!adminUserId) return NextResponse.json({ error: "未登录" }, { status: 401 });

    const { id: workspaceId } = await params;
    const body = await req.json();
    const { configs } = body as {
      configs: Array<{
        alert_type: string;
        threshold: number;
        email_enabled: boolean;
        enabled: boolean;
      }>;
    };

    const client = await getClient();
    try {
      await client.query("BEGIN");

      for (const cfg of configs) {
        await client.query(
          `INSERT INTO workspace_alert_config
             (workspace_id, alert_type, threshold, email_enabled, enabled, created_by)
           VALUES ($1, $2, $3, $4, $5, $6)
           ON CONFLICT (workspace_id, alert_type)
           DO UPDATE SET
             threshold = EXCLUDED.threshold,
             email_enabled = EXCLUDED.email_enabled,
             enabled = EXCLUDED.enabled,
             updated_at = NOW()`,
          [workspaceId, cfg.alert_type, cfg.threshold, cfg.email_enabled, cfg.enabled, adminUserId]
        );
      }

      await client.query("COMMIT");
      return NextResponse.json({ success: true });
    } catch {
      await client.query("ROLLBACK");
      throw "transaction error";
    } finally {
      client.release();
    }
  } catch (e) {
    console.error("Alert config update error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
