// functions/index.js
const { onRequest } = require("firebase-functions/v2/https");
const { setGlobalOptions } = require("firebase-functions/v2");
const cors = require("cors")({ origin: true });
require("dotenv").config();

const OpenAI = require("openai");
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

setGlobalOptions({ region: "us-central1", maxInstances: 10 });

exports.virtualTherapist = onRequest(async (req, res) => {
  return cors(req, res, async () => {
    if (req.method !== "POST") {
      res.set("Allow", "POST");
      return res.status(405).send("Only POST allowed");
    }

    const { message } = req.body || {};
    if (!message || typeof message !== "string") {
      return res.status(400).json({ error: "Missing 'message' string" });
    }

    try {
      const completion = await openai.chat.completions.create({
        model: "gpt-4o-mini",
        messages: [
          { role: "system", content: "You are a compassionate virtual therapist." },
          { role: "user", content: message },
        ],
      });
      const reply = completion.choices?.[0]?.message?.content ?? "";
      return res.status(200).json({ reply });
    } catch (err) {
      console.error("OpenAI error:", err?.response?.data || err?.message || err);
      return res.status(500).json({ error: "Internal Server Error" });
    }
  });
});
