const { Client } = require('../models/associations');
const { Op } = require('sequelize');

class ClientController {
    // Get all clients with search and pagination
    async getAllClients(req, res) {
        try {
            const {
                page = 1,
                limit = 10,
                search,
                actif,
                sort_by = 'created_at',
                sort_order = 'DESC'
            } = req.query;

            const offset = (parseInt(page) - 1) * parseInt(limit);
            const whereClause = {};

            // Search filter
            if (search) {
                whereClause[Op.or] = [
                    { nom: { [Op.like]: `%${search}%` } },
                    { prenom: { [Op.like]: `%${search}%` } },
                    { email: { [Op.like]: `%${search}%` } },
                    { telephone: { [Op.like]: `%${search}%` } }
                ];
            }

            // Active filter
            if (actif !== undefined) {
                whereClause.actif = actif === 'true';
            }

            const { count, rows } = await Client.findAndCountAll({
                where: whereClause,
                limit: parseInt(limit),
                offset: offset,
                order: [[sort_by, sort_order.toUpperCase()]],
                attributes: { exclude: ['updated_at'] }
            });

            res.json({
                success: true,
                data: {
                    clients: rows,
                    pagination: {
                        currentPage: parseInt(page),
                        totalPages: Math.ceil(count / parseInt(limit)),
                        totalItems: count,
                        itemsPerPage: parseInt(limit)
                    }
                }
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Erreur lors de la récupération des clients',
                error: error.message
            });
        }
    }

    // Get client by ID
    async getClientById(req, res) {
        try {
            const { id } = req.params;
            
            const client = await Client.findByPk(id, {
                include: [
                    {
                        association: 'reservations',
                        limit: 5,
                        order: [['date_reservation', 'DESC']]
                    },
                    {
                        association: 'commandes',
                        limit: 5,
                        order: [['date_commande', 'DESC']]
                    }
                ]
            });

            if (!client) {
                return res.status(404).json({
                    success: false,
                    message: 'Client non trouvé'
                });
            }

            res.json({
                success: true,
                data: client
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Erreur lors de la récupération du client',
                error: error.message
            });
        }
    }

    // Create new client
    async createClient(req, res) {
        try {
            const clientData = req.body;

            const client = await Client.create(clientData);

            res.status(201).json({
                success: true,
                message: 'Client créé avec succès',
                data: client
            });
        } catch (error) {
            if (error.name === 'SequelizeValidationError') {
                return res.status(400).json({
                    success: false,
                    message: 'Données invalides',
                    errors: error.errors.map(e => ({
                        field: e.path,
                        message: e.message
                    }))
                });
            }

            if (error.name === 'SequelizeUniqueConstraintError') {
                return res.status(400).json({
                    success: false,
                    message: 'Email déjà utilisé'
                });
            }

            res.status(500).json({
                success: false,
                message: 'Erreur lors de la création du client',
                error: error.message
            });
        }
    }

    // Update client
    async updateClient(req, res) {
        try {
            const { id } = req.params;
            const updateData = req.body;

            const client = await Client.findByPk(id);
            if (!client) {
                return res.status(404).json({
                    success: false,
                    message: 'Client non trouvé'
                });
            }

            await client.update(updateData);

            res.json({
                success: true,
                message: 'Client mis à jour avec succès',
                data: client
            });
        } catch (error) {
            if (error.name === 'SequelizeValidationError') {
                return res.status(400).json({
                    success: false,
                    message: 'Données invalides',
                    errors: error.errors.map(e => ({
                        field: e.path,
                        message: e.message
                    }))
                });
            }

            res.status(500).json({
                success: false,
                message: 'Erreur lors de la mise à jour du client',
                error: error.message
            });
        }
    }

    // Delete client
    async deleteClient(req, res) {
        try {
            const { id } = req.params;

            const client = await Client.findByPk(id);
            if (!client) {
                return res.status(404).json({
                    success: false,
                    message: 'Client non trouvé'
                });
            }

            await client.destroy();

            res.json({
                success: true,
                message: 'Client supprimé avec succès'
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Erreur lors de la suppression du client',
                error: error.message
            });
        }
    }

    // Get client statistics
    async getClientStats(req, res) {
        try {
            const totalClients = await Client.count();
            const activeClients = await Client.count({ where: { actif: true } });
            const inactiveClients = await Client.count({ where: { actif: false } });
            
            const topClients = await Client.findAll({
                order: [['points_fidelite', 'DESC']],
                limit: 5,
                attributes: ['nom', 'prenom', 'email', 'points_fidelite']
            });

            res.json({
                success: true,
                data: {
                    totalClients,
                    activeClients,
                    inactiveClients,
                    topClients
                }
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Erreur lors de la récupération des statistiques',
                error: error.message
            });
        }
    }
}

module.exports = new ClientController();
