import { NextRequest, NextResponse } from "next/server";
import { ScoutDraftRequestSchema, ScoutDraftResponseSchema, TaskStatus } from "@agent-bounty/contracts";
import { prisma } from "@/lib/prisma";
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 POST(request: NextRequest) {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return NextResponse.json({ error: "Unauthorized: Missing Bearer token" }, { status: 401 });
  }

  const token = authHeader.split(" ")[1];
  if (process.env.API_KEY && token !== process.env.API_KEY) {
    return NextResponse.json({ error: "Forbidden: Invalid API Key" }, { status: 403 });
  }

  try {
    const body = await request.json();
    const parsed = ScoutDraftRequestSchema.parse(body);

    // Validate scout_id exists and is whitelisted
    const scout = await prisma.agentProfile.findUnique({
      where: { agent_id: parsed.scout_id }
    });

    if (!scout || scout.status !== "WHITELISTED") {
      return NextResponse.json({ error: "Forbidden: Scout Agent is not whitelisted" }, { status: 403 });
    }

    // Create DRAFT task
    const task = await prisma.task.create({
      data: {
        title: parsed.title,
        description: parsed.description,
        status: TaskStatus.DRAFT,
        difficulty: "COMPONENT", // Defaulting for Phase 1
        scope_clarity_score: 1.0,
        reward_amount: parsed.reward_amount,
        reward_currency: parsed.reward_currency,
        required_stack: parsed.required_stack,
        scout_id: scout.agent_id,
        acceptance_criteria: {
          validation_mode: "VITEST_UNIT",
          test_file_content: parsed.test_file_content,
        }
      }
    });

    // Create Stripe Checkout Session
    // 試營運期間：如果賞金小於等於 20 美元 ($20.00 = 2000 cents)，則由官方贊助（免刷卡直接 OPEN）
    if (parsed.reward_amount <= 2000) {
      await prisma.task.update({
        where: { id: task.id },
        data: { 
          status: TaskStatus.OPEN,
          stripe_checkout_session_id: "promo_free_bounty",
          stripe_payment_intent_id: "promo_free_bounty_intent" // Skip auth hold
        }
      });

      const responseData = {
        task_id: task.id,
        checkout_url: `${process.env.NEXT_PUBLIC_SITE_URL || 'https://agent.wooo.work'}/tasks/${task.id}`,
        status: TaskStatus.OPEN,
      };

      ScoutDraftResponseSchema.parse(responseData);
      return NextResponse.json(responseData);
    }

    if (!stripe) throw new Error("Stripe is not initialized");
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      mode: "payment",
      line_items: [
        {
          price_data: {
            currency: parsed.reward_currency.toLowerCase(),
            product_data: {
              name: `VibeWork Task: ${parsed.title}`,
              description: "Auth-Hold. Funds will only be captured when task is judged PASS.",
            },
            unit_amount: parsed.reward_amount,
          },
          quantity: 1,
        },
      ],
      payment_intent_data: {
        capture_method: "manual",
        metadata: {
          task_id: task.id,
          scout_id: scout.agent_id,
        }
      },
      // You should set these to actual frontend URLs
      success_url: `${process.env.NEXT_PUBLIC_SITE_URL || 'https://agent.wooo.work'}/tasks/${task.id}?success=true`,
      cancel_url: `${process.env.NEXT_PUBLIC_SITE_URL || 'https://agent.wooo.work'}/tasks/create`,
    });

    // Save session ID so webhook can find it
    await prisma.task.update({
      where: { id: task.id },
      data: { stripe_checkout_session_id: session.id }
    });

    const responseData = {
      task_id: task.id,
      checkout_url: session.url!,
      status: TaskStatus.DRAFT,
    };

    ScoutDraftResponseSchema.parse(responseData); // strict output validation

    return NextResponse.json(responseData);

  } catch (error: any) {
    console.error("[Scout API Error]", error);
    if (error.name === "ZodError") {
      return NextResponse.json({ error_type: "InvalidParams", message: error.errors }, { status: 400 });
    }
    return NextResponse.json({ error_type: "InternalError", message: error.message }, { status: 500 });
  }
}
