import express from 'express';
import pool from '../db.js';
import { GoogleGenerativeAI } from '@google/generative-ai';
const router = express.Router();
router.post('/', async (req, res) => {
    try {
        const { message } = req.body; // Ignore frontend context, use fresh DB data
        const apiKey = process.env.GEMINI_API_KEY;
        if (!apiKey) {
            return res.status(500).json({ error: 'AI API Key not configured' });
        }
        // Fetch real-time data from all major tables
        const [customers] = await pool.query('SELECT name, company, email, phone, balance, vat_number FROM customers');
        const [projects] = await pool.query('SELECT name, status, budget, start_date, end_date FROM projects');
        const [invoices] = await pool.query(`
            SELECT i.invoice_number, i.total_amount, i.status, i.due_date, c.name as customer_name 
            FROM invoices i 
            LEFT JOIN customers c ON i.customer_id = c.id 
            ORDER BY i.date DESC LIMIT 50
        `);
        const [expenses] = await pool.query('SELECT description, amount, category, date FROM expenses ORDER BY date DESC LIMIT 50');
        const [quotations] = await pool.query(`
            SELECT q.quotation_number, q.grand_total, q.status, c.name as customer_name 
            FROM quotations q 
            LEFT JOIN customers c ON q.customer_id = c.id 
            ORDER BY q.date DESC LIMIT 20
        `);
        // Calculate summaries
        const totalRevenue = invoices.reduce((sum, i) => sum + Number(i.total_amount || 0), 0);
        const totalOutstanding = invoices.filter((i) => i.status !== 'Paid').reduce((sum, i) => sum + Number(i.total_amount || 0), 0);
        const activeProjects = projects.filter((p) => p.status === 'In Progress').length;
        const dbContext = `
System Data Timestamp: ${new Date().toLocaleString()}

FINANCIAL SNAPSHOT:
- Total Invoiced Revenue: AED ${totalRevenue.toLocaleString()}
- Outstanding Payments: AED ${totalOutstanding.toLocaleString()}
- Active Projects: ${activeProjects}

CUSTOMERS (${customers.length}):
${JSON.stringify(customers, null, 2)}

PROJECTS (${projects.length}):
${JSON.stringify(projects, null, 2)}

RECENT INVOICES (Last 50):
${JSON.stringify(invoices, null, 2)}

RECENT EXPENSES (Last 50):
${JSON.stringify(expenses, null, 2)}

RECENT QUOTATIONS (Last 20):
${JSON.stringify(quotations, null, 2)}
        `;
        const genAI = new GoogleGenerativeAI(apiKey);
        const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash-exp" });
        const systemInstruction = `
You are the "Golden Castel Pro AI Decision Engine".
Your goal is to answer questions about the business using ONLY the provided database records.

RULES:
1.  **Scope**: You have access to Customers, Projects, Invoices, Expenses, and Quotations.
2.  **Privacy**: Do not reveal internal IDs (UUIDs) unless asked.
3.  **Tone**: Professional, executive summary style. Concise.
4.  **Unknowns**: If the data isn't in the provided JSON context, say "I don't have that record."
5.  **Currency**: All monetary values are in AED.
6.  **Formatting**: Use bolding for important numbers (e.g., **AED 5,000**).

CONTEXT DATA:
${dbContext}
    `;
        const chat = model.startChat({
            history: [
                {
                    role: "user",
                    parts: [{ text: systemInstruction }],
                },
                {
                    role: "model",
                    parts: [{ text: "Acknowledged. I have ingested the latest business data. I am ready to answer queries regarding customers, financials, and projects." }],
                },
            ],
        });
        const result = await chat.sendMessage(message);
        const response = result.response.text();
        res.json({ response });
    }
    catch (error) {
        console.error('AI Error:', error);
        res.status(500).json({ error: 'Failed to generate response', details: error.message });
    }
});
export default router;
//# sourceMappingURL=ai.js.map