"use server";

import { prisma } from "@/lib/prisma";
import { logA2aTrafficEvent } from "@/lib/a2a-traffic";
import {
  getProposalPackage,
  sanitizeAgentId,
  TREASURY_USDC_ADDRESS,
  TREASURY_WALLET_LABEL,
  VIBEWORK_SITE_URL,
} from "@/lib/a2a-growth";
import { TaskDifficulty, TaskStatus } from "@agent-bounty/contracts";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import Stripe from "stripe";

const stripe = process.env.STRIPE_SECRET_KEY
  ? new Stripe(process.env.STRIPE_SECRET_KEY, {
      apiVersion: "2026-05-27.dahlia",
    })
  : null;

function getString(formData: FormData, key: string) {
  const value = formData.get(key);
  return typeof value === "string" ? value.trim() : "";
}

function parseBudgetCents(value: string) {
  const normalized = value.replace(/[,$]/g, "").trim();
  const dollars = Number.parseFloat(normalized);
  if (!Number.isFinite(dollars) || dollars <= 0) {
    return 50000;
  }
  return Math.max(Math.round(dollars * 100), 10000);
}

function resolveDifficulty(budgetCents: number) {
  if (budgetCents >= 200000) return TaskDifficulty.EPIC;
  if (budgetCents >= 50000) return TaskDifficulty.VIEW;
  return TaskDifficulty.COMPONENT;
}

function parseStack(value: string) {
  const stack = value
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean)
    .slice(0, 12);

  return stack.length ? stack : ["AI Agent", "VibeWork"];
}

function buildSuccessUrl(taskId: string, params?: Record<string, string>) {
  const url = new URL("/propose/success", VIBEWORK_SITE_URL);
  url.searchParams.set("task_id", taskId);
  if (params) {
    for (const [key, value] of Object.entries(params)) {
      url.searchParams.set(key, value);
    }
  }
  return url.toString();
}

function buildCancelUrl(referralAgent: string, packageId: string) {
  const url = new URL("/propose", VIBEWORK_SITE_URL);
  if (referralAgent) url.searchParams.set("ref_agent", referralAgent);
  url.searchParams.set("package", packageId);
  url.searchParams.set("cancelled", "true");
  return url.toString();
}

export async function createDemandProposal(formData: FormData) {
  const requestHeaders = await headers();
  const packageId = getString(formData, "packageId");
  const proposalPackage = getProposalPackage(packageId);
  const referralAgent = sanitizeAgentId(getString(formData, "refAgent"));
  const source = getString(formData, "source") || "vibework-propose";
  const campaign = getString(formData, "campaign") || "direct";
  const paymentMethod = getString(formData, "paymentMethod") || "stripe";

  const proposerName = getString(formData, "proposerName");
  const proposerEmail = getString(formData, "proposerEmail");
  const company = getString(formData, "company");
  const title = getString(formData, "title");
  const description = getString(formData, "description");
  const desiredOutcome = getString(formData, "desiredOutcome");
  const urgency = getString(formData, "urgency") || "normal";
  const requiredStack = parseStack(getString(formData, "requiredStack"));
  const budgetCents = parseBudgetCents(getString(formData, "budgetUsd"));

  if (!title || title.length < 6) {
    throw new Error("請提供至少 6 個字元的需求標題。");
  }
  if (!description || description.length < 30) {
    throw new Error("請提供至少 30 個字元的需求描述，讓 AI Agent 可以判斷範圍。");
  }
  if (!proposerEmail || !proposerEmail.includes("@")) {
    throw new Error("請提供有效 email，方便後續 scope review 聯繫。");
  }

  if (referralAgent) {
    await prisma.agentProfile.upsert({
      where: { agent_id: referralAgent },
      update: {
        discovery_source: "DEMAND_PROPOSAL_REFERRAL",
        capabilities: {
          growth_referral: true,
          campaign,
          source,
        },
      },
      create: {
        agent_id: referralAgent,
        type: "SCOUT",
        status: "PENDING",
        discovery_source: "DEMAND_PROPOSAL_REFERRAL",
        capabilities: {
          growth_referral: true,
          campaign,
          source,
        },
      },
    });
  }

  const task = await prisma.task.create({
    data: {
      title: `[Proposal] ${title}`,
      description: [
        `Demand proposer: ${proposerName || "Unknown"}`,
        `Email: ${proposerEmail}`,
        company ? `Company: ${company}` : null,
        `Urgency: ${urgency}`,
        `Desired outcome: ${desiredOutcome || "Needs scoping"}`,
        "",
        description,
      ]
        .filter(Boolean)
        .join("\n"),
      status: TaskStatus.DRAFT,
      difficulty: resolveDifficulty(budgetCents),
      scope_clarity_score: 0.82,
      reward_amount: budgetCents,
      reward_currency: "USD",
      required_stack: requiredStack,
      acceptance_criteria: {
        validation_mode: "VITEST_UNIT",
        test_file_content:
          "Proposal intake placeholder. Platform review must convert this draft into scoped acceptance criteria before the bounty is opened.",
        desired_outcome: desiredOutcome,
        source,
        campaign,
      },
      is_priority: proposalPackage.id === "priority",
      is_private: true,
      referred_by_agent: referralAgent || null,
      scout_id: referralAgent || null,
      created_by_agent: "demand-proposal-intake",
    },
  });

  await prisma.auditEvent.create({
    data: {
      actorType: referralAgent ? "AGENT" : "USER",
      actorId: referralAgent || proposerEmail,
      action: "DEMAND_PROPOSAL_INTAKE_CREATED",
      entityType: "TASK",
      entityId: task.id,
      metadata: {
        proposer_email: proposerEmail,
        proposer_name: proposerName || null,
        company: company || null,
        package_id: proposalPackage.id,
        proposal_fee_cents: proposalPackage.feeCents,
        budget_cents: budgetCents,
        source,
        campaign,
        referral_agent: referralAgent || null,
        payment_method: paymentMethod,
      },
    },
  });

  if (referralAgent) {
    await logA2aTrafficEvent({
      headers: requestHeaders,
      fallbackAgentId: referralAgent,
      action: "EXTERNAL_DEMAND_PROPOSAL_INTAKE_CREATED",
      surface: "propose/action",
      entityType: "TASK",
      entityId: task.id,
      reason: "referred_demand_proposal_submitted",
      metadata: {
        package_id: proposalPackage.id,
        proposal_fee_cents: proposalPackage.feeCents,
        budget_cents: budgetCents,
        source,
        campaign,
        referral_agent: referralAgent,
        payment_method: paymentMethod,
        response_status: 200,
        response_summary: "demand_proposal_intake_created",
      },
    });
  }

  if (paymentMethod === "wallet" || !stripe) {
    await prisma.auditEvent.create({
      data: {
        actorType: "SYSTEM",
        actorId: "proposal-payment",
        action: "DEMAND_PROPOSAL_WALLET_PAYMENT_INSTRUCTIONS",
        entityType: "TASK",
        entityId: task.id,
        metadata: {
          package_id: proposalPackage.id,
          amount_cents: proposalPackage.feeCents,
          treasury_wallet_label: TREASURY_WALLET_LABEL,
          treasury_usdc_address_present: Boolean(TREASURY_USDC_ADDRESS),
        },
      },
    });

    if (referralAgent) {
      await logA2aTrafficEvent({
        headers: requestHeaders,
        fallbackAgentId: referralAgent,
        action: "EXTERNAL_DEMAND_PROPOSAL_WALLET_PAYMENT_PENDING",
        surface: "propose/action",
        entityType: "TASK",
        entityId: task.id,
        reason: "wallet_payment_instructions_issued",
        metadata: {
          package_id: proposalPackage.id,
          amount_cents: proposalPackage.feeCents,
          referral_agent: referralAgent,
          response_status: 200,
          response_summary: "wallet_payment_instructions_issued",
        },
      });
    }

    redirect(buildSuccessUrl(task.id, {
      payment: "wallet",
      package: proposalPackage.id,
    }));
  }

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    mode: "payment",
    customer_email: proposerEmail,
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: `VibeWork ${proposalPackage.name}`,
            description: proposalPackage.description,
          },
          unit_amount: proposalPackage.feeCents,
        },
        quantity: 1,
      },
    ],
    metadata: {
      intent: "DEMAND_PROPOSAL_FEE",
      task_id: task.id,
      referral_agent: referralAgent,
      proposal_fee_cents: String(proposalPackage.feeCents),
      package_id: proposalPackage.id,
      budget_cents: String(budgetCents),
      source,
      campaign,
    },
    success_url: `${buildSuccessUrl(task.id, {
      payment: "stripe",
      package: proposalPackage.id,
    })}&session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: buildCancelUrl(referralAgent, proposalPackage.id),
  });

  await prisma.task.update({
    where: { id: task.id },
    data: { stripe_checkout_session_id: session.id },
  });

  if (!session.url) {
    throw new Error("Stripe checkout session URL is missing.");
  }

  if (referralAgent) {
    await logA2aTrafficEvent({
      headers: requestHeaders,
      fallbackAgentId: referralAgent,
      action: "EXTERNAL_DEMAND_PROPOSAL_CHECKOUT_STARTED",
      surface: "propose/action",
      entityType: "TASK",
      entityId: task.id,
      reason: "stripe_checkout_started",
      metadata: {
        stripe_session_id: session.id,
        package_id: proposalPackage.id,
        amount_cents: proposalPackage.feeCents,
        referral_agent: referralAgent,
        response_status: 303,
        response_summary: "stripe_checkout_started",
      },
    });
  }

  redirect(session.url);
}
