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

export const runtime = "nodejs";

// GET /api/admin/projects/[id]/billing — get project billing info
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  try {
    const billingRes = await query(
      `SELECT pb.project_uuid, pb.balance, pb.currency, pb.updated_at, pb.created_at
       FROM project_billing pb WHERE pb.project_uuid = $1`,
      [id]
    );
    const historyRes = await query(
      `SELECT uid, project, user, amount, currency, reason, extra, created_at
       FROM project_billing_history
       WHERE project = $1
       ORDER BY created_at DESC
       LIMIT 100`,
      [id]
    );
    const billing = billingRes.rows[0];
    return NextResponse.json({
      billing: billing ? {
        balance: billing.balance,
        currency: billing.currency,
        updated_at: billing.updated_at,
        created_at: billing.created_at,
      } : null,
      history: historyRes.rows.map((r: Record<string, unknown>) => ({
        uid: String(r.uid),
        amount: String(r.amount),
        currency: r.currency,
        reason: r.reason,
        description: r.extra ? (r.extra as Record<string, unknown>).description : null,
        created_at: r.created_at,
      })),
    });
  } catch (e) {
    logError("Project billing error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

// POST /api/admin/projects/[id]/billing — add credit
export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const body = await req.json();
  const amount = parseFloat(body.amount);
  const description = String(body.description || "Admin 充值");

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

  try {
    await transaction(async (tx) => {
      // Upsert project_billing
      await tx.query(
        `INSERT INTO project_billing (project_uuid, balance, currency, updated_at, created_at)
         VALUES ($1, $2, 'USD', NOW(), NOW())
         ON CONFLICT (project_uuid) DO UPDATE SET
           balance = project_billing.balance + $2,
           updated_at = NOW()`,
        [id, amount]
      );

      // Insert history
      await tx.query(
        `INSERT INTO project_billing_history (uid, project, user, amount, currency, reason, extra, created_at)
         VALUES (gen_random_uuid(), $1, NULL, $2, 'USD', 'admin_credit', ('{"description":"' || $3 || '"}')::jsonb, NOW())`,
        [id, amount, description]
      );
    });

    return NextResponse.json({ ok: true, amount });
  } catch (e) {
    logError("Project add credit error:", e);
    return NextResponse.json({ error: "充值失败" }, { status: 500 });
  }
}
