import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { checkRateLimit } from "@/lib/rate-limit";
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const VALID_TRADES = [
  "Labourer",
  "Steel Fixer",
  "Formworker",
  "Carpenter",
  "Electrician",
  "Plumber",
  "Concreter",
  "Bricklayer",
  "Painter",
  "Roofer",
  "Scaffolder",
  "Tiler",
  "Plasterer",
  "Welder",
  "Crane Operator",
  "Excavator Operator",
];

const VALID_AVAILABILITY = ["full-time", "casual", "weekends", "flexible"];

interface ParsedProfile {
  trade: string;
  experience_years: number;
  location: string;
  availability: string;
}

export async function POST(request: NextRequest) {
  try {
    // Auth check
    const supabase = await createClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();

    if (authError || !user) {
      return NextResponse.json(
        { error: "Unauthorized" },
        { status: 401 }
      );
    }

    // Rate limiting
    const ip = request.ip ?? request.headers.get("x-forwarded-for") ?? "unknown";
    const rateLimit = await checkRateLimit(ip);

    if (!rateLimit.allowed) {
      return NextResponse.json(
        { error: "Rate limit exceeded. Please try again later." },
        { status: 429 }
      );
    }

    // Parse request body
    const body = await request.json();
    const { transcript } = body;

    if (!transcript || typeof transcript !== "string") {
      return NextResponse.json(
        { error: "No transcript provided" },
        { status: 400 }
      );
    }

    // Parse using GPT-4o-mini
    const completion = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [
        {
          role: "system",
          content: `Extract construction worker profile data from this transcript. Return JSON with:
- trade (string, one of: Labourer, Steel Fixer, Formworker, Carpenter, Electrician, Plumber, Concreter, Bricklayer, Painter, Roofer, Scaffolder, Tiler, Plasterer, Welder, Crane Operator, Excavator Operator)
- experience_years (number)
- location (string - suburb/area in Sydney)
- availability (one of: full-time, casual, weekends, flexible)

Respond with ONLY valid JSON, no markdown formatting or explanations.`,
        },
        {
          role: "user",
          content: transcript,
        },
      ],
      response_format: { type: "json_object" },
      temperature: 0.3,
    });

    const content = completion.choices[0].message.content;

    if (!content) {
      return NextResponse.json(
        { error: "Failed to parse transcript" },
        { status: 500 }
      );
    }

    const parsed = JSON.parse(content) as ParsedProfile;

    // Validate the parsed data
    const errors: string[] = [];

    // Validate trade
    const matchedTrade = VALID_TRADES.find(
      (t) => t.toLowerCase() === parsed.trade?.toLowerCase()
    );
    if (!matchedTrade) {
      errors.push(`Invalid trade: "${parsed.trade}"`);
    }

    // Validate experience_years
    const experienceYears = Number(parsed.experience_years);
    if (isNaN(experienceYears) || experienceYears < 0 || experienceYears > 60) {
      errors.push(`Invalid experience years: "${parsed.experience_years}"`);
    }

    // Validate location
    if (!parsed.location || parsed.location.trim().length < 2) {
      errors.push("Location is required");
    }

    // Validate availability
    const matchedAvailability = VALID_AVAILABILITY.find(
      (a) => a.toLowerCase() === parsed.availability?.toLowerCase().replace(/\s+/g, "-")
    );
    if (!matchedAvailability) {
      errors.push(`Invalid availability: "${parsed.availability}"`);
    }

    // Return parsed data with validation info
    return NextResponse.json({
      data: {
        trade: matchedTrade || parsed.trade,
        experience_years: experienceYears || 0,
        location: parsed.location?.trim() || "",
        availability: matchedAvailability || parsed.availability,
      },
      raw: parsed,
      validationErrors: errors.length > 0 ? errors : undefined,
      isValid: errors.length === 0,
      remaining: rateLimit.remaining,
    });
  } catch (error) {
    console.error("Parse profile error:", error);
    return NextResponse.json(
      { error: "Failed to parse profile data" },
      { status: 500 }
    );
  }
}
