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

export const runtime = "nodejs";

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await req.json() as {
      amount?: number;
      description?: string;
    };
    const { amount = 0, description = "" } = body;

    if (!amount || amount <= 0) {
      return NextResponse.json({ error: "金额必须大于 0" }, { status: 400 });
    }

    // Get workspace info first
    const wsResult = await query(
      `SELECT id, slug, name FROM workspace WHERE id = $1 AND deleted_at IS NULL`,
      [id]
    );
    if (!wsResult.rows.length) {
      return NextResponse.json({ error: "Workspace 不存在" }, { status: 404 });
    }
    const workspace = wsResult.rows[0] as { id: string; slug: string; name: string };

    // Get billing account
    const billingResult = await query(
      `SELECT id, balance, currency FROM workspace_billing WHERE workspace_id = $1`,
      [id]
    );

    let currency = "USD";
    if (billingResult.rows.length) {
      currency = (billingResult.rows[0].currency as string) || "USD";
    }

    // Use transaction for atomicity
    const client = await getClient();
    try {
      await client.query("BEGIN");

      if (billingResult.rows.length) {
        // Update existing balance
        await client.query(
          `UPDATE workspace_billing
           SET balance = balance + $1, currency = $2, updated_at = NOW()
           WHERE workspace_id = $3`,
          [amount, currency, id]
        );
      } else {
        // Create billing record if doesn't exist
        await client.query(
          `INSERT INTO workspace_billing (workspace_id, balance, currency, monthly_quota, total_spent, updated_at, created_at)
           VALUES ($1, $2, $3, 0, 0, NOW(), NOW())`,
          [id, amount, currency]
        );
      }

      // Insert billing history
      await client.query(
        `INSERT INTO workspace_billing_history
           (workspace_id, user_id, amount, reason, extra, currency)
         VALUES ($1, NULL, $2, 'admin_credit', $3, $4)`,
        [id, amount, JSON.stringify({ description: description || "Admin 手动充值" }), currency]
      );

      await client.query("COMMIT");
    } catch (innerError) {
      await client.query("ROLLBACK");
      throw innerError;
    } finally {
      client.release();
    }

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    const adminUsername = req.headers.get("x-admin-username") || "unknown";
    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "update",
      resource: "workspace_billing",
      resourceId: id,
      requestParams: { workspaceSlug: workspace.slug, amount, description },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ success: true, amount, currency });
  } catch (e) {
    console.error("Add workspace credit error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
