import { prisma } from "@/lib/prisma";
import { asA2aAgentActorId } from "@/lib/a2a-traffic";
import { Prisma } from "../../prisma/generated/client";
import { TaskStatus } from "@agent-bounty/contracts";

type ProposalFeeTrafficContext = {
  actor_type: "AGENT" | "USER";
  actor_id: string;
  request_id: string;
  source_ip: string;
  user_agent: string;
  is_public_ip: boolean;
  request_actor_headers?: Record<string, string | number | boolean | null>;
};

export type ProposalFeeCaptureInput = {
  taskId: string;
  referralAgent?: string | null;
  proposalFeeCents: number;
  paymentProvider: "stripe" | "wallet";
  paymentReference: string;
  idempotencyKey: string;
  responseStatus?: "captured" | "verified";
  packageId?: string | null;
  source?: string | null;
  campaign?: string | null;
  verificationNote?: string | null;
  trafficContext?: ProposalFeeTrafficContext | null;
};

function positiveCents(value: number) {
  if (!Number.isFinite(value)) return 0;
  return Math.max(0, Math.floor(value));
}

function externalTrafficContextForReferral(referralAgent: string): ProposalFeeTrafficContext {
  return {
    actor_type: "AGENT",
    actor_id: asA2aAgentActorId(referralAgent),
    request_id: `admin-wallet-${Date.now()}`,
    source_ip: "admin-verification",
    user_agent: "vibework-admin-wallet-verifier",
    is_public_ip: false,
    request_actor_headers: {},
  };
}

export async function recordDemandProposalFeeCaptured(input: ProposalFeeCaptureInput) {
  const proposalFeeCents = positiveCents(input.proposalFeeCents);
  const affiliateFeeCents = input.referralAgent ? Math.floor(proposalFeeCents * 0.1) : 0;
  const responseStatus = input.responseStatus || (input.paymentProvider === "wallet" ? "verified" : "captured");
  const trafficContext =
    input.referralAgent && input.paymentProvider === "wallet" && !input.trafficContext
      ? externalTrafficContextForReferral(input.referralAgent)
      : input.trafficContext;

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

  if (!task) {
    throw new Error(`Proposal task not found: ${input.taskId}`);
  }

  const existingCapture = await prisma.ledgerEntry.findUnique({
    where: { idempotency_key: input.idempotencyKey },
  });

  if (existingCapture) {
    return {
      task_id: input.taskId,
      duplicate: true,
      ledger_entry_id: existingCapture.id,
      affiliate_fee_cents: affiliateFeeCents,
    };
  }

  const result = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
    const ledger = await tx.ledgerEntry.create({
      data: {
        task_id: input.taskId,
        phase: "proposal_fee_captured",
        idempotency_key: input.idempotencyKey,
        stripe_object_id: input.paymentReference,
        response_status: responseStatus,
        http_status: 200,
      },
    });

    await tx.task.update({
      where: { id: input.taskId },
      data: {
        stripe_payment_intent_id: input.paymentReference,
        status: TaskStatus.DRAFT,
      },
    });

    if (input.referralAgent) {
      await tx.agentProfile.upsert({
        where: { agent_id: input.referralAgent },
        update: {
          discovery_source: "DEMAND_PROPOSAL_PAID_REFERRAL",
        },
        create: {
          agent_id: input.referralAgent,
          type: "SCOUT",
          status: "PENDING",
          discovery_source: "DEMAND_PROPOSAL_PAID_REFERRAL",
          capabilities: {
            growth_referral: true,
            source: input.source || input.paymentProvider,
          },
        },
      });

      await tx.scoutReputation.upsert({
        where: { scout_id: input.referralAgent },
        update: {
          successful_conversions: { increment: 1 },
        },
        create: {
          scout_id: input.referralAgent,
          successful_conversions: 1,
        },
      });

      const existingAffiliate = await tx.affiliateLedger.findFirst({
        where: {
          scout_id: input.referralAgent,
          task_id: input.taskId,
        },
      });

      if (!existingAffiliate && affiliateFeeCents > 0) {
        await tx.affiliateLedger.create({
          data: {
            scout_id: input.referralAgent,
            task_id: input.taskId,
            amount: affiliateFeeCents,
            currency: input.paymentProvider === "wallet" ? "USDC" : "USD",
            status: "PENDING",
          },
        });
      }
    }

    await tx.auditEvent.create({
      data: {
        actorType: "SYSTEM",
        actorId: input.paymentProvider === "wallet" ? "wallet-verifier" : "stripe-webhook",
        action: "DEMAND_PROPOSAL_FEE_CAPTURED",
        entityType: "TASK",
        entityId: input.taskId,
        metadata: {
          payment_provider: input.paymentProvider,
          payment_reference: input.paymentReference,
          fee_cents: proposalFeeCents,
          currency: input.paymentProvider === "wallet" ? "USDC" : "USD",
          package_id: input.packageId || null,
          referral_agent: input.referralAgent || null,
          affiliate_fee_cents: affiliateFeeCents,
          source: input.source || null,
          campaign: input.campaign || null,
          verification_note: input.verificationNote || null,
        },
      },
    });

    if (input.referralAgent && trafficContext) {
      await tx.auditEvent.create({
        data: {
          actorType: trafficContext.actor_type,
          actorId: trafficContext.actor_id,
          action: "EXTERNAL_DEMAND_PROPOSAL_FEE_CAPTURED",
          entityType: "TASK",
          entityId: input.taskId,
          reason: "referred_demand_proposal_payment_captured",
          metadata: {
            payment_provider: input.paymentProvider,
            payment_reference: input.paymentReference,
            fee_cents: proposalFeeCents,
            currency: input.paymentProvider === "wallet" ? "USDC" : "USD",
            package_id: input.packageId || null,
            referral_agent: input.referralAgent,
            affiliate_fee_cents: affiliateFeeCents,
            source: input.source || null,
            campaign: input.campaign || null,
            verification_note: input.verificationNote || null,
            request_id: trafficContext.request_id,
            source_ip: trafficContext.source_ip,
            user_agent: trafficContext.user_agent,
            is_public_ip: trafficContext.is_public_ip,
            surface: input.paymentProvider === "wallet" ? "admin/wallet-verification" : "stripe/webhook",
            request_actor_headers: trafficContext.request_actor_headers || {},
            response_status: 200,
            response_summary: "demand_proposal_fee_captured",
          },
        },
      });
    }

    return ledger;
  });

  return {
    task_id: input.taskId,
    duplicate: false,
    ledger_entry_id: result.id,
    affiliate_fee_cents: affiliateFeeCents,
  };
}
