import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { adminUnauthorizedResponse, isAdminRequestAuthorized } from "@/lib/admin-auth";
import { recordDemandProposalFeeCaptured } from "@/lib/proposal-payment-ledger";
import { sanitizeAgentId } from "@/lib/a2a-growth";

function asRecord(value: unknown) {
  return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
}

function stringValue(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function positiveInteger(value: unknown) {
  const parsed = typeof value === "number" ? value : Number.parseInt(String(value || ""), 10);
  if (!Number.isFinite(parsed) || parsed <= 0) return 0;
  return Math.floor(parsed);
}

function normalizePaymentReference(value: string) {
  return value.trim().replace(/\s+/g, "").slice(0, 180);
}

export async function POST(request: NextRequest) {
  if (!isAdminRequestAuthorized(request)) {
    return adminUnauthorizedResponse();
  }

  try {
    const body = asRecord(await request.json().catch(() => ({})));
    const taskId = stringValue(body.task_id || body.taskId);
    const paymentReference = normalizePaymentReference(
      stringValue(body.payment_reference || body.tx_hash || body.txHash)
    );
    const overrideAmountCents = positiveInteger(body.amount_cents || body.amountCents);
    const verificationNote = stringValue(body.verification_note || body.note);

    if (!taskId) {
      return NextResponse.json({ error: "task_id is required" }, { status: 400 });
    }

    if (!paymentReference) {
      return NextResponse.json({ error: "payment_reference or tx_hash is required" }, { status: 400 });
    }

    const task = await prisma.task.findUnique({
      where: { id: taskId },
      select: {
        id: true,
        title: true,
        referred_by_agent: true,
        scout_id: true,
      },
    });

    if (!task) {
      return NextResponse.json({ error: "Proposal task not found" }, { status: 404 });
    }

    const intakeEvent = await prisma.auditEvent.findFirst({
      where: {
        action: "DEMAND_PROPOSAL_INTAKE_CREATED",
        entityType: "TASK",
        entityId: task.id,
      },
      orderBy: { createdAt: "desc" },
      select: { metadata: true },
    });

    const metadata = asRecord(intakeEvent?.metadata);
    const feeCents = overrideAmountCents || positiveInteger(metadata.proposal_fee_cents);

    if (!feeCents) {
      return NextResponse.json({
        error: "Unable to resolve proposal fee amount. Provide amount_cents.",
      }, { status: 400 });
    }

    const referralAgent = sanitizeAgentId(
      task.referred_by_agent || task.scout_id || stringValue(metadata.referral_agent)
    );

    const result = await recordDemandProposalFeeCaptured({
      taskId: task.id,
      referralAgent: referralAgent || null,
      proposalFeeCents: feeCents,
      paymentProvider: "wallet",
      paymentReference: `wallet:${paymentReference}`,
      idempotencyKey: `proposal-wallet-fee:${paymentReference}`,
      responseStatus: "verified",
      packageId: stringValue(metadata.package_id) || null,
      source: stringValue(metadata.source) || "wallet-verification",
      campaign: stringValue(metadata.campaign) || null,
      verificationNote: verificationNote || null,
    });

    return NextResponse.json({
      success: true,
      duplicate: result.duplicate,
      task_id: result.task_id,
      ledger_entry_id: result.ledger_entry_id,
      referral_agent: referralAgent || null,
      fee_cents: feeCents,
      affiliate_fee_cents: result.affiliate_fee_cents,
      payment_reference: paymentReference,
    });
  } catch (error: unknown) {
    console.error("[Wallet Proposal Verification Error]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
