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

// PATCH /api/admin/daily-report/recipients/[id] — update recipient
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await req.json() as { email?: string; name?: string; is_active?: boolean };
    const { email, name, is_active } = body;

    const updates: string[] = [];
    const vals: unknown[] = [];
    let idx = 1;

    if (email !== undefined) {
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        return NextResponse.json({ error: "无效的邮箱地址" }, { status: 400 });
      }
      updates.push(`email = $${idx++}`);
      vals.push(email.toLowerCase());
    }
    if (name !== undefined) {
      updates.push(`name = $${idx++}`);
      vals.push(name);
    }
    if (is_active !== undefined) {
      updates.push(`is_active = $${idx++}`);
      vals.push(is_active);
    }

    if (updates.length === 0) {
      return NextResponse.json({ error: "没有需要更新的字段" }, { status: 400 });
    }

    updates.push(`updated_at = NOW()`);
    vals.push(id);

    const result = await query(
      `UPDATE internal_email_recipients SET ${updates.join(", ")} WHERE id = $${idx} RETURNING *`,
      vals
    );

    if (!result.rows.length) {
      return NextResponse.json({ error: "收件人不存在" }, { status: 404 });
    }

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    await createAuditLog({
      userId: adminUserId,
      username: req.headers.get("x-admin-username") || "unknown",
      action: "update",
      resource: "internal_email_recipient",
      resourceId: id,
      requestParams: body,
    });

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

// DELETE /api/admin/daily-report/recipients/[id] — remove recipient
export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const result = await query(
      `DELETE FROM internal_email_recipients WHERE id = $1 RETURNING id`,
      [id]
    );

    if (!result.rows.length) {
      return NextResponse.json({ error: "收件人不存在" }, { status: 404 });
    }

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    await createAuditLog({
      userId: adminUserId,
      username: req.headers.get("x-admin-username") || "unknown",
      action: "delete",
      resource: "internal_email_recipient",
      resourceId: id,
    });

    return NextResponse.json({ success: true });
  } catch (e) {
    logError("Delete recipient error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
