import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { GoogleGenerativeAI } from "@google/generative-ai";

export const maxDuration = 30; // Serverless function timeout

export async function POST(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser || currentUser.role !== 'admin') {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const resolvedParams = await params;
        const jobId = resolvedParams.id;

        const job = await prisma.job.findUnique({
            where: { id: jobId },
            include: { employer: true }
        });

        if (!job) {
            return NextResponse.json({ error: "Job not found" }, { status: 404 });
        }

        const apiKey = process.env.GEMINI_API_KEY;
        if (!apiKey) {
            return NextResponse.json({
                error: "AI Analysis is not configured. Please add GEMINI_API_KEY to your environment variables."
            }, { status: 501 });
        }

        const genAI = new GoogleGenerativeAI(apiKey);
        // Using gemini-2.5-flash since 3.0 Pro SDK might map differently depending on versions, 2.5-flash is stable for text
        const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });

        const prompt = `
You are an expert HR content reviewer. Analyze the following job posting for quality, clarity, and safety. 
Provide a strictly valid JSON response without markdown formatting like \`\`\`json. 
The JSON must have the following structure:
{
  "recommendation": "Approve" | "Request Changes" | "Reject",
  "confidenceScore": <number between 0 and 100>,
  "contentQualityScore": <number between 0 and 10>,
  "contentFeedback": "<short sentence>",
  "fraudRisk": "Low" | "Moderate" | "High",
  "fraudFeedback": "<short sentence tracking company info / spam risk>",
  "missingRequirements": ["<missing thing 1>", "<missing thing 2>", ...],
  "wordCount": <number of words in description>
}

Job Title: ${job.title}
Company: ${job.company}
Location Type: ${job.work_location_type}
Salary: ${job.salary_min} - ${job.salary_max} ${job.currency}
Description:
${job.description}
`;

        const result = await model.generateContent(prompt);
        const responseText = result.response.text();

        // Clean up markdown in case the model ignored instructions
        const cleanedText = responseText.replace(/```json\n?|```\n?/g, '').trim();
        const analysis = JSON.parse(cleanedText);

        return NextResponse.json({
            success: true,
            analysis
        });

    } catch (error: any) {
        console.error("Error analyzing job:", error);
        return NextResponse.json(
            { error: "Failed to perform AI analysis", details: error.message },
            { status: 500 }
        );
    }
}
