"use server";

import { prisma } from "@/lib/prisma";
import { TaskStatus, TaskDifficulty } from "@agent-bounty/contracts";
import { cookies } 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;

export async function createTask(formData: FormData) {
  const cookieStore = await cookies();
  const referralAgent = cookieStore.get("vw_referral_agent")?.value;

  const title = formData.get("title") as string;
  const description = formData.get("description") as string;
  const rewardAmount = parseInt(formData.get("rewardAmount") as string, 10) * 100; // to cents
  const requiredStack = (formData.get("requiredStack") as string).split(",").map(s => s.trim());
  const testFileContent = formData.get("testFileContent") as string;
  const isPriority = formData.get("isPriority") === "on";
  const isPrivate = formData.get("isPrivate") === "on";
  
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://agent.wooo.work";

  const task = await prisma.task.create({
    data: {
      title,
      description,
      status: TaskStatus.DRAFT,
      difficulty: TaskDifficulty.COMPONENT,
      scope_clarity_score: 1.0,
      reward_amount: rewardAmount,
      reward_currency: "USD",
      required_stack: requiredStack,
      acceptance_criteria: {
        validation_mode: "VITEST_UNIT",
        test_file_content: testFileContent
      },
      is_priority: isPriority,
      is_private: isPrivate,
      referred_by_agent: referralAgent || null
    }
  });

  if (!stripe) {
    throw new Error("Stripe is not configured");
  }

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    mode: "payment",
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: `VibeWork Task: ${title}`,
            description: "Auth-Hold. Funds will only be captured when task is judged PASS.",
          },
          unit_amount: rewardAmount,
        },
        quantity: 1,
      },
      ...(isPriority ? [{
        price_data: {
          currency: "usd",
          product_data: { name: "🚀 Priority Fast-Track Fee", description: "Boost visibility and pin to top" },
          unit_amount: 500, // $5
        },
        quantity: 1,
      }] : []),
      ...(isPrivate ? [{
        price_data: {
          currency: "usd",
          product_data: { name: "🕵️‍♂️ Private Bounty Fee", description: "Hide from public feeds" },
          unit_amount: 1000, // $10
        },
        quantity: 1,
      }] : [])
    ],
    payment_intent_data: {
      capture_method: "manual"
    },
    success_url: `${siteUrl}/tasks/${task.id}?success=true`,
    cancel_url: `${siteUrl}/tasks/create`,
  });

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

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

  redirect(session.url);
}
