const express = require('express');
const Service = require('../models/Service.cjs');
const { auth } = require('../middleware/auth.cjs');
const router = express.Router();

// Get all services for the company
router.get('/', auth, async (req, res) => {
  try {
    const services = await Service.find({ company: req.user.company._id, isActive: true });
    res.json(services);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching services' });
  }
});
// In services router
// services.cjs
router.get('/public/portal/:slug', async (req, res) => {
  try {
    const company = await Company.findOne({
      'publicPortal.slug': req.params.slug.toLowerCase().trim(),
      'publicPortal.enabled': true
    })
      .select('_id name') // ← adiciona name (útil para header)
      .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();

    res.json({
      companyId: company._id,
      companyName: company.name,
      services
    });
  } catch (err) {
    console.error('Erro em /public/portal/:slug:', err);
    res.status(500).json({ message: 'Erro interno ao carregar serviços' });
  }
});
// Em services.cjs
router.get('/public/company/:companyId', async (req, res) => {
  try {
    const services = await Service.find({
      company: req.params.companyId,
      isActive: true
    })
      .select('name description basePrice unit allowedInstallments penaltyPercentagePerInstallment')
      .lean();

    res.json(services);
  } catch (err) {
    res.status(500).json({ message: 'Erro ao carregar serviços' });
  }
});

// Create a new service
router.post('/', auth, async (req, res) => {
  try {
    const service = new Service({
      ...req.body,
      company: req.user.company._id
    });
    await service.save();
    res.status(201).json(service);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// Update a service
router.put('/:id', auth, async (req, res) => {
  try {
    const service = await Service.findOneAndUpdate(
      { _id: req.params.id, company: req.user.company._id },
      req.body,
      { new: true }
    );
    if (!service) return res.status(404).json({ message: 'Service not found' });
    res.json(service);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

module.exports = router;