import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { TaskStatus } from "@agent-bounty/contracts";

export const dynamic = "force-dynamic";

const getPayoutMode = (task: {
  reward_amount: number;
  stripe_checkout_session_id: string | null;
  stripe_payment_intent_id: string | null;
}) => {
  if (task.stripe_checkout_session_id === "promo_free_bounty" && task.stripe_payment_intent_id) {
    return "BETA_ZERO_FRICTION";
  }
  if (task.stripe_payment_intent_id) {
    return "PAYMENT_AUTHORIZED";
  }
  return "PAYMENT_PENDING";
};

export async function GET(request: Request) {
  const tasks = await prisma.task.findMany({
    where: { status: TaskStatus.OPEN },
    orderBy: { created_at: "desc" },
    select: {
      id: true,
      title: true,
      description: true,
      reward_amount: true,
      reward_currency: true,
      required_stack: true,
      status: true,
      difficulty: true,
      scope_clarity_score: true,
      created_at: true,
      updated_at: true,
      scout_id: true,
      stripe_checkout_session_id: true,
      stripe_payment_intent_id: true,
    },
  });

  const publicPayload = tasks.map((task) => ({
    task_id: task.id,
    title: task.title,
    status: task.status,
    difficulty: task.difficulty,
    reward_amount_cents: task.reward_amount,
    reward_display: `$${(task.reward_amount / 100).toFixed(2)} ${task.reward_currency}`,
    required_stack: task.required_stack,
    scope_clarity_score: task.scope_clarity_score,
    created_at: task.created_at.toISOString(),
    updated_at: task.updated_at.toISOString(),
    source: task.scout_id ? "scout" : "human",
    payout_mode: getPayoutMode(task),
    task_url: `https://agent.wooo.work/tasks/${task.id}`,
  }));

  const sourceIp =
    request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
    request.headers.get("x-real-ip") ??
    "unknown";

  void prisma.auditEvent.create({
    data: {
      actorType: "USER",
      actorId: `open-tasks:${sourceIp}`,
      action: "EXTERNAL_LIST_OPEN_TASKS",
      entityType: "TASK",
      entityId: "open-tasks",
      afterState: {
        total_open: publicPayload.length,
      },
      reason: "external-discovery",
      metadata: {
        source: "public-open-tasks",
        user_agent: request.headers.get("user-agent") ?? "unknown",
      },
    },
  }).catch(() => {});

  return NextResponse.json({
    platform: "VibeWork",
    version: "v1",
    discovery_mode: "ai-first",
    beta_program: "VibeWork Beta Zero Friction + 0% Platform Fee for promoted tasks",
    tasks: publicPayload,
    total_open: publicPayload.length,
    last_refreshed_at: new Date().toISOString(),
  });
}
