import express from 'express';
import { Groq } from 'groq-sdk';
import { requireAuth } from '../middleware/auth.js';

const router = express.Router();
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });

router.post('/', requireAuth, async (req, res, next) => {
  try {
    const { messages } = req.body;
    if (!messages || !Array.isArray(messages)) {
      return res.status(400).json({ error: { code: 'INVALID_INPUT', message: 'messages array is required' } });
    }

    // Prepend system instruction
    const systemMessage = {
      role: 'system',
      content: "You are the official AI Assistant for Fix It - Painting & Washing. You are an expert in automotive denting, body painting, ceramic coating, and professional car washing. Keep your answers concise, helpful, and friendly. Advise users to book a service if they need bodywork or a premium wash.",
    };

    const apiMessages = [systemMessage, ...messages.map(m => ({
      role: m.isUser ? 'user' : 'assistant',
      content: m.text
    }))];

    const chatCompletion = await groq.chat.completions.create({
      messages: apiMessages,
      model: "openai/gpt-oss-120b",
      temperature: 0.7,
      max_completion_tokens: 8192,
      top_p: 1,
      stream: false,
    });

    const reply = chatCompletion.choices[0]?.message?.content || "I'm sorry, I couldn't process that request right now.";
    return res.json({ reply });
  } catch (err) {
    next(err);
  }
});

export default router;
