export const dynamic = 'force-dynamic';
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { z } from "zod";

const SubmitBidRequestSchema = z.object({
  task_id: z.string().uuid(),
  agent_id: z.string().min(1).max(120),
  developer_wallet: z
    .string()
    .regex(/^(0x[a-fA-F0-9]{40}|acct_[a-zA-Z0-9]+)$/)
    .optional(),
  proposed_reward: z.number().int().positive().max(1_000_000_00), // in cents
  estimated_duration_hours: z.number().positive().max(24 * 30),
  quality_guarantee: z.string().max(1000).optional(),
  broker_agent_id: z.string().max(120).optional(),
  broker_fee_percentage: z.number().min(0).max(100).optional()
});

export async function POST(request: NextRequest) {
  const PUBLIC_BETA_TOKEN = (process.env.PUBLIC_MCP_BETA_TOKEN || "").trim();

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

    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];
    const isBetaToken = !!PUBLIC_BETA_TOKEN && token === PUBLIC_BETA_TOKEN;
    const isValidServerKey = process.env.API_KEY && token === process.env.API_KEY;

    if (!isValidServerKey && !isBetaToken) {
      return NextResponse.json({ error: "Forbidden: Invalid API Key" }, { status: 403 });
    }

    const agent = await prisma.agentProfile.findUnique({
      where: { agent_id: parsed.agent_id }
    });

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

    let validAgent = agent;
    if (parsed.developer_wallet && !agent.wallet_address) {
      validAgent = await prisma.agentProfile.update({
        where: { agent_id: parsed.agent_id },
        data: { wallet_address: parsed.developer_wallet },
      });
    } else if (parsed.developer_wallet && agent.wallet_address && agent.wallet_address !== parsed.developer_wallet) {
      return NextResponse.json({ error: "Forbidden: developer_wallet does not match registered agent wallet" }, { status: 403 });
    }

    const result = await prisma.$transaction(async (tx) => {
      const task = await tx.task.findUnique({ where: { id: parsed.task_id } });
      if (!task || task.status !== "OPEN") {
        throw new Error("Task is not OPEN or does not exist");
      }

      // ==========================================
      // PHASE 20: STAKING ENFORCEMENT
      // ==========================================
      if (task.difficulty === "EPIC" && validAgent.tier !== "PREMIUM") {
        throw new Error("Forbidden: EPIC difficulty tasks require the PREMIUM tier. Please deposit at least 500 USDC stake using the A2A_STAKE_DEPOSIT method.");
      }
      
      const existingBid = await tx.bidProposal.findFirst({
        where: { task_id: parsed.task_id, agent_id: validAgent.agent_id }
      });
      
      if (existingBid) {
        throw new Error("Agent has already submitted a bid for this task");
      }

      const newBid = await tx.bidProposal.create({
        data: {
          task_id: parsed.task_id,
          agent_id: validAgent.agent_id,
          proposed_reward: parsed.proposed_reward,
          estimated_duration_hours: parsed.estimated_duration_hours,
          quality_guarantee: parsed.quality_guarantee,
          broker_agent_id: parsed.broker_agent_id,
          broker_fee_percentage: parsed.broker_fee_percentage,
          status: "PENDING"
        }
      });
      
      return newBid;
    });

    return NextResponse.json({
      bid_id: result.id,
      task_id: result.task_id,
      status: result.status,
      proposed_reward: result.proposed_reward
    });
  } catch (error: unknown) {
    console.error("[submit_bid] Error:", error);
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: "Invalid request", details: error.flatten() }, { status: 400 });
    }
    if (
      typeof error === "object" &&
      error !== null &&
      "code" in error &&
      (error as { code?: unknown }).code === "P2002"
    ) {
      return NextResponse.json({ error: "Agent has already submitted a bid for this task" }, { status: 409 });
    }
    return NextResponse.json({ error: error instanceof Error ? error.message : "Internal Server Error" }, { status: 400 });
  }
}
