import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { a2aUnauthorizedResponse, isA2aRequestAuthorized } from "@/lib/a2a-auth";

export async function POST(req: Request) {
  if (!isA2aRequestAuthorized(req)) {
    return a2aUnauthorizedResponse();
  }

  if (process.env.ENABLE_MOCK_SETTLEMENT !== "true") {
    return NextResponse.json({ error: "Settlement worker is disabled" }, { status: 403 });
  }

  try {
    const { task_id } = await req.json();

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

    // 1. Fetch Task and Bid Proposal
    const task = await prisma.task.findUnique({
      where: { id: task_id },
      include: {
        bid_proposals: {
          where: { status: "ACCEPTED" }
        }
      }
    });

    if (!task) return NextResponse.json({ error: "Task not found" }, { status: 404 });
    if (task.status !== "COMPLETED") {
      return NextResponse.json({ error: "Task is not COMPLETED. Cannot settle." }, { status: 400 });
    }

    if (!task.builder_id) {
      return NextResponse.json({ error: "Task has no builder assigned" }, { status: 400 });
    }

    // 2. Fetch Builder Wallet Address
    const builderProfile = await prisma.agentProfile.findUnique({
      where: { agent_id: task.builder_id }
    });

    if (!builderProfile?.wallet_address) {
      return NextResponse.json({ error: "Builder does not have a wallet_address registered" }, { status: 400 });
    }

    const acceptedBid = task.bid_proposals[0];
    const totalAmount = task.reward_amount; // e.g. in cents or USDC smallest unit

    // 3. Calculate Distribution (System Fee 10%, Broker Fee X%)
    const SYSTEM_FEE_PCT = 10;
    let brokerAmount = 0;
    let builderAmount = 0;
    let systemAmount = 0;
    let brokerAddress = "0x0000000000000000000000000000000000000000";

    systemAmount = Math.floor(totalAmount * (SYSTEM_FEE_PCT / 100));

    if (acceptedBid?.broker_agent_id && acceptedBid?.broker_fee_percentage) {
      const brokerProfile = await prisma.agentProfile.findUnique({
        where: { agent_id: acceptedBid.broker_agent_id }
      });
      if (brokerProfile?.wallet_address) {
        brokerAmount = Math.floor(totalAmount * (acceptedBid.broker_fee_percentage / 100));
        brokerAddress = brokerProfile.wallet_address;
      }
    }

    builderAmount = totalAmount - systemAmount - brokerAmount;

    // 4. Mock settlement recording. Real settlement must run in a private worker.
    const txHash = "mock_tx_" + Date.now();

    // Simulate Web3 Delay
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // 5. Update Task Ledger/Status (Optional, if you have a ledger)
    // We log it out for now.
    console.log(`[Web3 Settlement] Task ${task_id} settled. TX: ${txHash}. Builder: ${builderAmount}, Broker: ${brokerAmount}, System: ${systemAmount}`);

    return NextResponse.json({
      success: true,
      message: "Mock settlement recorded",
      tx_hash: txHash,
      distribution: {
        builder_address: builderProfile.wallet_address,
        builder_amount: builderAmount,
        broker_address: brokerAddress !== "0x0000000000000000000000000000000000000000" ? brokerAddress : null,
        broker_amount: brokerAmount,
        system_fee: systemAmount,
      }
    });

  } catch (error: unknown) {
    console.error("[Settle API Error]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
