// routes/public.cjs
const express = require('express');
const helmet = require('helmet');
const { body, validationResult } = require('express-validator');
const crypto = require('crypto');

const Company = require('../models/Company.cjs');
const Service = require('../models/Service.cjs');
const Requisition = require('../models/Requisition.cjs');
const { auth } = require('../middleware/auth.cjs');

const router = express.Router();

// ────────────────────────────────────────────────
// CSP ajustado para permitir Lucide + Tailwind + inline scripts (necessário para o teu template)
router.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: [
        "'self'",
        "'unsafe-inline'",                // permite <script> inline no template
        "https://cdn.jsdelivr.net",
        "https://cdnjs.cloudflare.com"
      ],
      styleSrc: [
        "'self'",
        "'unsafe-inline'",
        "https://cdn.jsdelivr.net",
        "https://cdnjs.cloudflare.com"     // ← corrigido: permite Lucide CSS
      ],
      imgSrc: ["'self'", "data:", "https:"],
      connectSrc: ["'self'", "https://*"],
      fontSrc: ["'self'", "https://cdnjs.cloudflare.com", "data:"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameSrc: ["'self'"],
    },
  },
  referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));


// ────────────────────────────────────────────────
// GET /public/portal/:slug  → public portal config + services
// GET /public/portal/:slug – API (JSON para frontend React)
// GET /public/portal/:slug – API JSON para o frontend React
router.get('/portal/:slug', async (req, res) => {
  try {
    const { slug } = req.params;

    const company = await Company.findOne({
      'publicPortal.slug': slug.toLowerCase().trim(),
      'publicPortal.enabled': true
    })
      .select('name email phone website logo address currency publicPortal') // inclui variant
      .lean();

    if (!company) {
      return res.status(404).json({ message: 'Portal não encontrado ou desativado' });
    }

    const services = await Service.find({
      company: company._id,
      isActive: true
    })
      .select('name description basePrice unit allowedInstallments penaltyPercentagePerInstallment')
      .lean();

    const token = crypto.randomBytes(32).toString('hex');

    res.json({
      company: {
        _id: company._id,
        name: company.name,
        email: company.email,
        phone: company.phone,
        website: company.website,
        logo: company.logo,
        address: company.address,
        currency: company.currency,
        publicPortal: company.publicPortal  // ← contém enabled, slug, variant...
      },
      services,
      formToken: token
    });
  } catch (err) {
    console.error('Erro na API /public/portal/:slug:', err);
    res.status(500).json({ message: 'Erro interno ao carregar o portal' });
  }
});

router.get('/', auth, async (req, res) => {
  try {
    const templates = await PublicPortalTemplate.find({
      $or: [
        { company: req.user.company._id },
        { isBuiltIn: true }
      ]
    })
      .select('name description isDefault isBuiltIn')
      .sort({ isDefault: -1, name: 1 })
      .lean();

    res.json(templates);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Erro ao listar templates' });
  }
});



module.exports = router;