import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { createAuditLog } from "@/lib/log";

export const runtime = "nodejs";

async function ensureTablesExist() {
  try {
    await query(`
      CREATE TABLE IF NOT EXISTS internal_email_recipients (
        id          BIGSERIAL PRIMARY KEY,
        email       VARCHAR(255) NOT NULL,
        name        VARCHAR(255) NOT NULL DEFAULT '',
        is_active   BOOLEAN NOT NULL DEFAULT true,
        created_by  BIGINT NOT NULL DEFAULT 0,
        created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
      )
    `);
    await query(`CREATE INDEX IF NOT EXISTS idx_internal_email_recipients_email ON internal_email_recipients (LOWER(email))`);
    await query(`
      CREATE TABLE IF NOT EXISTS admin_ai_config (
        id BIGSERIAL PRIMARY KEY, config_key VARCHAR(100) NOT NULL UNIQUE,
        config_value TEXT NOT NULL DEFAULT '', updated_by BIGINT, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      )
    `);
  } catch { /* ignore */ }
}

// GET /api/admin/daily-report/recipients — list all recipients
export async function GET() {
  await ensureTablesExist();
  try {
    const result = await query(
      `SELECT id, email, name, is_active, created_at::text as created_at, created_by
       FROM internal_email_recipients
       ORDER BY created_at DESC`
    );
    return NextResponse.json({ recipients: result.rows });
  } catch (e) {
    logError("List recipients error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

// POST /api/admin/daily-report/recipients — add recipient
export async function POST(req: NextRequest) {
  await ensureTablesExist();
  try {
    const body = await req.json() as { email?: string; name?: string };
    const { email, name = "" } = body;

    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({ error: "无效的邮箱地址" }, { status: 400 });
    }

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);

    const result = await query(
      `INSERT INTO internal_email_recipients (email, name, created_by)
       VALUES ($1, $2, $3)
       RETURNING id, email, name, is_active, created_at::text as created_at`,
      [email.toLowerCase(), name, adminUserId]
    );

    await createAuditLog({
      userId: adminUserId,
      username: req.headers.get("x-admin-username") || "unknown",
      action: "create",
      resource: "internal_email_recipient",
      resourceId: String(result.rows[0]?.id),
      requestParams: { email },
    });

    return NextResponse.json(result.rows[0], { status: 201 });
  } catch (e: unknown) {
    const err = e as { code?: string };
    if (err?.code === "23505") {
      return NextResponse.json({ error: "该邮箱已存在" }, { status: 409 });
    }
    logError("Add recipient error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
