const admin = require("firebase-admin");
const logger = require("firebase-functions/logger");
const auth = require("../utils/auth");

exports.generateTTSV2 = async (req, res) => {
  try {
    const decodedToken = await auth.authenticateUser(req);

    logger.info("[generateTTSV2] Request from user:", {
      uid: decodedToken.uid,
      email: decodedToken.email,
    });

    const {text, voiceConfig} = req.body.data || {};

    if (!text) {
      res.status(400).json({error: "Text parameter is required"});
      return;
    }

    if (text.length > 5000) {
      res.status(400).json({error: "Text too long (max 5000 characters)"});
      return;
    }

    const {Storage} = require("@google-cloud/storage");
    const storage = new Storage();
    const bucketName = admin.storage().bucket().name;
    const bucket = storage.bucket(bucketName);

    const {generateTTS} = require("../generateTTS");
    const result = await generateTTS(text, storage, bucket, voiceConfig);

    logger.info("[generateTTSV2] ✓ Success", {
      cached: result.cached,
      cacheKey: result.cacheKey,
    });

    res.status(200).json({
      audioUrl: result.audioUrl,
      cached: result.cached,
      cacheKey: result.cacheKey,
    });
  } catch (error) {
    logger.error("[generateTTSV2] ✗ Error:", {
      error: error.message,
      code: error.code,
    });

    if (error.code === "PERMISSION_DENIED") {
      res.status(403).json({error: "Permission denied. Check Google Cloud TTS API is enabled."});
    } else if (error.code === "QUOTA_EXCEEDED") {
      res.status(429).json({error: "TTS quota exceeded. Try again later."});
    } else {
      res.status(500).json({error: error.message});
    }
  }
};
