'use server';

import { PrismaClient } from '@prisma/client';
import { GoogleGenAI } from '@google/genai';
import { revalidatePath } from 'next/cache';

const prisma = new PrismaClient();

export async function generatePropertyDescription(tags: string) {
  // Fetch API key from DB
  const setting = await prisma.setting.findUnique({ where: { key: 'gemini_api_key' } });
  const apiKey = setting?.value || process.env.GEMINI_API_KEY;

  if (!apiKey) {
    throw new Error("Gemini API key not configured. Please set it in Super Admin.");
  }

  const ai = new GoogleGenAI({ apiKey });
  
  const prompt = `Write a professional, compelling real estate property description in English based on these details: ${tags}. Make it appealing to potential buyers or renters.`;
  
  try {
    const response = await ai.models.generateContent({
      model: 'gemini-2.5-flash',
      contents: prompt,
    });
    
    return response.text;
  } catch (error) {
    console.error("AI Generation failed", error);
    throw new Error("Failed to generate description");
  }
}

export async function saveProperty(formData: FormData) {
  const title = formData.get('title') as string;
  const price = parseFloat(formData.get('price') as string);
  const locationGps = formData.get('locationGps') as string;
  const aiDescription = formData.get('aiDescription') as string;

  const property = await prisma.property.create({
    data: {
      title,
      price,
      locationGps,
      aiDescription,
      agentId: 1, // hardcoded for demo, normally from session
    }
  });

  revalidatePath('/agent/properties');
  return property.id;
}
