import type { NextApiRequest, NextApiResponse } from 'next';
import prisma from '@/prisma/config';

/**
 * Simple property creation endpoint.
 * Expects JSON body with: agentId, title, price, locationGps, area, city, block, images (array of URLs).
 * Generates an AI description using Gemini API key from env (if provided).
 */
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const {
    agentId,
    title,
    price,
    locationGps,
    area,
    city,
    block,
    images,
  } = req.body as any;

  // Basic validation (could be extended)
  if (!agentId || !title || !price) {
    return res.status(400).json({ error: 'Missing required fields' });
  }

  // Generate AI description if GEMINI_API_KEY is set
  let aiDescription = null;
  const geminiKey = process.env.GEMINI_API_KEY;
  if (geminiKey) {
    try {
      const response = await fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' + geminiKey, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contents: [{
            role: 'user',
            parts: [{ text: `Write a professional real‑estate description (English & Arabic) for a property with the following details:\nTitle: ${title}\nPrice: ${price}\nLocation: ${city || ''} ${block || ''}\nArea: ${area || ''}\nImages: ${Array.isArray(images) ? images.join(', ') : ''}` }],
          }],
        }),
      });
      const data = await response.json();
      aiDescription = data?.candidates?.[0]?.content?.parts?.[0]?.text || null;
    } catch (e) {
      console.error('AI generation error:', e);
    }
  }

  try {
    const property = await prisma.property.create({
      data: {
        agentId,
        title,
        price,
        locationGps,
        area,
        city,
        block,
        images: images ? JSON.stringify(images) : undefined,
        aiDescription: aiDescription ?? undefined,
      },
    });
    res.status(201).json(property);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to create property' });
  }
}
