import { NextRequest, NextResponse } from "next/server";
import OpenAI from "openai";
import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
import { sanitizeInput } from "@/lib/sanitize";
import { withCSRFProtection } from "@/lib/csrf";

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

// Rate limit: 5 requests per 15 minutes per IP (expensive AI call)
const AI_RATE_LIMIT = 5;
const AI_WINDOW_MS = 15 * 60 * 1000;

const handler = async (request: NextRequest) => {
  try {
    // --- Rate limiting ---
    const clientIP = getClientIP(request);
    const rateLimit = checkRateLimit(`ai-profile:${clientIP}`, AI_RATE_LIMIT, AI_WINDOW_MS);
    
    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }
    
    const { trade, experience, location, availability } = await request.json();

    if (!trade || experience === undefined || !location || !availability) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 }
      );
    }

    // Sanitize inputs to prevent prompt injection
    const sanitizedTrade = sanitizeInput(trade, { maxLength: 100 });
    const sanitizedLocation = sanitizeInput(location, { maxLength: 200 });
    const sanitizedAvailability = sanitizeInput(availability, { maxLength: 50 });
    
    // Validate experience is a number
    const experienceYears = parseInt(experience, 10);
    if (isNaN(experienceYears) || experienceYears < 0 || experienceYears > 100) {
      return NextResponse.json(
        { error: "Invalid experience value" },
        { status: 400 }
      );
    }

    const prompt = `You are an expert construction industry recruiter. Based on the following information about a construction worker, generate a professional profile.

Worker Information:
- Trade: ${sanitizedTrade}
- Years of Experience: ${experienceYears} years
- Location: ${sanitizedLocation}
- Availability: ${sanitizedAvailability}

Generate a JSON response with:
1. bio: A professional 2-3 sentence bio (50-80 words) highlighting their expertise, experience, and work style
2. skills: An array of 6-10 relevant technical skills for their trade (specific tools, techniques, materials)
3. certifications: An array of 3-5 common/recommended certifications for their trade (actual Australian construction certifications)

Make it sound professional but approachable. Focus on practical skills and experience.

Return ONLY valid JSON in this exact format:
{
  "bio": "string",
  "skills": ["skill1", "skill2", ...],
  "certifications": ["cert1", "cert2", ...]
}`;

    const completion = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [
        {
          role: "system",
          content: "You are a construction industry expert. Always respond with valid JSON only.",
        },
        {
          role: "user",
          content: prompt,
        },
      ],
      temperature: 0.7,
      response_format: { type: "json_object" },
    });

    const content = completion.choices[0]?.message?.content;
    if (!content) {
      throw new Error("No response from AI");
    }

    const generated = JSON.parse(content);

    return NextResponse.json({
      bio: generated.bio || "",
      skills: generated.skills || [],
      certifications: generated.certifications || [],
    });
  } catch (error) {
    console.error("AI generation error:", error);
    return NextResponse.json(
      { error: "Failed to generate profile" },
      { status: 500 }
    );
  }
}

// Apply CSRF protection to the handler
export const POST = withCSRFProtection(handler);
