import { PrismaClient, TaskStatus } from "../apps/web/prisma/generated/client";
import { capturePayment, executePayout } from "../apps/web/src/lib/payment";

const prisma = new PrismaClient();

async function main() {
  const taskId = process.argv[2];
  if (!taskId) {
    console.error("Please provide a Task ID: pnpm dlx tsx scripts/approve_and_payout.ts <task_id>");
    process.exit(1);
  }

  console.log(`🔍 Approving Task: ${taskId}...`);

  const task = await prisma.task.findUnique({
    where: { id: taskId },
    include: { claims: { where: { status: "PENDING_REVIEW" }, orderBy: { created_at: 'desc' }, take: 1 } }
  });

  if (!task || task.claims.length === 0) {
    console.error("Task not found or no claim in PENDING_REVIEW status.");
    process.exit(1);
  }

  const claim = task.claims[0];

  await prisma.$transaction(async (tx) => {
    // 1. Mark Claim and Task as COMPLETED
    await tx.claim.update({
      where: { id: claim.id },
      data: { status: TaskStatus.COMPLETED }
    });
    await tx.task.update({
      where: { id: task.id },
      data: { status: TaskStatus.COMPLETED }
    });

    // 2. Capture funds from the task creator
    console.log("💰 Capturing funds...");
    const captureKey = `capture-${task.id}-${Date.now()}`;
    await capturePayment(tx, task.id, captureKey);

    // 3. Execute Payout to the Agent's developer wallet
    console.log(`🏦 Routing payout to agent wallet: ${claim.developer_wallet}...`);
    const payoutKey = `payout-${claim.id}-${Date.now()}`;
    // Deduct routing fee conceptually, or pay the full held amount if the fee was deducted at sub-task creation
    await executePayout(tx, task.id, claim.developer_wallet, claim.held_amount, claim.held_currency, payoutKey);
  });

  console.log("🎉 Payout Successful! The agent has been paid.");
}

main().catch(console.error).finally(() => prisma.$disconnect());
