import { NextResponse } from 'next/server';
import { GoogleGenerativeAI } from '@google/generative-ai';

export async function POST(req: Request) {
  try {
    const { lead } = await req.json();
    if (!lead) {
      return NextResponse.json({ error: 'Lead data is required' }, { status: 400 });
    }

    const apiKey = process.env.GEMINI_API_KEY;
    if (!apiKey) {
      // Fallback to template if no API key is provided
      const template = `Subject: Quick question for ${lead.name}
      
Hi ${lead.name} team,

I noticed you're doing great work in the ${lead.category || 'industry'}. I'm reaching out because I'd love to discuss how we can help you grow further.

Best,
[Your Name]`;
      
      return NextResponse.json({ 
        outreach: template,
        isAiGenerated: false,
        warning: 'Set GEMINI_API_KEY for personalized AI outreach'
      });
    }

    const genAI = new GoogleGenerativeAI(apiKey);
    const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

    const prompt = `
      You are a professional sales outreach expert. 
      Generate a short, personalized, and high-converting cold email for the following business:
      Name: ${lead.name}
      Category: ${lead.category}
      Location: ${lead.address}
      Website: ${lead.website}
      
      The email should:
      1. Reference their specific business or category.
      2. Mention that we found them via LeadForge.
      3. Propose a quick 5-min chat about optimizing their business.
      4. Be under 100 words.
      5. Include a [Subject] line at the top.
    `;

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

    return NextResponse.json({ 
      outreach: text,
      isAiGenerated: true 
    });
    
  } catch (error: any) {
    console.error('Outreach generation error:', error);
    return NextResponse.json({ error: 'Failed to generate outreach' }, { status: 500 });
  }
}
