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

const router = express.Router();

// Get all clients
router.get('/', auth, async (req, res) => {
  try {
    const { search, origin, active, page = 1, limit = 12 } = req.query;
    
    const filter = { company: req.user.company._id };
    
    // 1. Filtro de Ativo/Inativo
    if (active !== undefined) {
      filter.isActive = active === 'true';
    }
    
    // 2. Filtro de Origem (Corrigindo o filtro internal/external)
    if (origin && origin !== 'all') {
      filter.origin = origin;
    }
    
    // 3. Busca em Tempo Real (Substituindo $text por $regex para ser menos "preguiçoso")
    if (search) {
      filter.$or = [
        { name: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } },
        { taxId: { $regex: search, $options: 'i' } }
      ];
    }

    const clients = await Client.find(filter)
      .sort({ createdAt: -1 }) // Mostrar os mais recentes primeiro
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await Client.countDocuments(filter);

    res.json({
      clients,
      pagination: {
        current: Number(page),
        pages: Math.ceil(total / limit),
        total
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
});

// Get client by ID
router.get('/:id', auth, async (req, res) => {
  try {
    const client = await Client.findOne({
      _id: req.params.id,
      company: req.user.company._id
    });

    if (!client) {
      return res.status(404).json({ message: 'Client not found' });
    }

    res.json(client);
  } catch (error) {
    console.error('Get client error:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Create new client (Internal via Auth)
router.post('/', auth, async (req, res) => {
  try {
    const clientData = {
      ...req.body,
      company: req.user.company._id,
      // Garante que clientes criados por utilizadores logados sejam marcados como internos
      origin: 'internal' 
    };

    // Opcional: Higienização básica para garantir que campos sensíveis 
    // não sejam sobrescritos por engano via req.body
    const client = new Client(clientData);
    await client.save();

    res.status(201).json(client);
  } catch (error) {
    // Tratamento de erro específico para campos duplicados (ex: Email ou TaxID)
    if (error.code === 11000) {
      return res.status(400).json({ 
        message: 'A client with this email or Tax ID already exists.' 
      });
    }

    console.error('Create client error:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Update client
router.put('/:id', auth, async (req, res) => {
  try {
    const client = await Client.findOneAndUpdate(
      {
        _id: req.params.id,
        company: req.user.company._id
      },
      req.body,
      { new: true, runValidators: true }
    );

    if (!client) {
      return res.status(404).json({ message: 'Client not found' });
    }

    res.json(client);
  } catch (error) {
    console.error('Update client error:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Delete client
router.delete('/:id', auth, async (req, res) => {
  try {
    const client = await Client.findOneAndDelete({
      _id: req.params.id,
      company: req.user.company._id
    });

    if (!client) {
      return res.status(404).json({ message: 'Client not found' });
    }

    res.json({ message: 'Client deleted successfully' });
  } catch (error) {
    console.error('Delete client error:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;