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";

// GET /api/admin/daily-report/recipients — list all recipients
export async function GET() {
  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("[recipients] List error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

// POST /api/admin/daily-report/recipients — add recipient
export async function POST(req: NextRequest) {
  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("[recipients] Add error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
