const express = require('express');
const joi = require('joi');
const Lead = require('../models/Lead');
const { auth, requireActivePlan } = require('../middleware/auth');
const checkLimit = require('../middleware/limit-checker');

const router = express.Router();

router.get('/', auth, async (req, res) => {
    try {
        let query = {};
        if (!req.user.isSuperAdmin) {
            query = { createdBy: req.user._id };
        }

        const leads = await Lead.find(query).sort({ createdAt: -1 });
        res.status(200).json({
            status: 'success',
            results: leads.length,
            data: { leads }
        });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
});

router.post('/', auth, requireActivePlan, checkLimit('leads'), async (req, res) => {
    const schema = joi.object({
        name: joi.string().required(),
        phone: joi.string().required(),
        fields: joi.array().items(joi.object({
            name: joi.string().required(),
            value: joi.any()
        })),
        tags: joi.array().items(joi.string())
    });

    try {
        const data = await schema.validateAsync(req.body);
        const lead = new Lead({
            ...data,
            createdBy: req.user._id
        });
        await lead.save();

        res.status(201).json({
            status: 'success',
            data: { lead }
        });
    } catch (err) {
        res.status(400).json({ status: 'error', message: err.message });
    }
});

router.post('/bulk', auth, requireActivePlan, checkLimit('leads'), async (req, res) => {
    const schema = joi.array().items(joi.object({
        name: joi.string().required(),
        phone: joi.string().required(),
        fields: joi.array().items(joi.object({
            name: joi.string().required(),
            value: joi.any()
        })),
        tags: joi.array().items(joi.string())
    }));

    try {
        const data = await schema.validateAsync(req.body);
        const leadsWithUser = data.map(lead => ({
            ...lead,
            createdBy: req.user._id
        }));
        const leads = await Lead.insertMany(leadsWithUser);

        res.status(201).json({
            status: 'success',
            results: leads.length,
            data: { leads }
        });
    } catch (err) {
        res.status(400).json({ status: 'error', message: err.message });
    }
});

router.patch('/bulk/tags', auth, async (req, res) => {
    const schema = joi.object({
        ids: joi.array().items(joi.string().required()).required(),
        tags: joi.array().items(joi.string().required()).required()
    });

    try {
        const { ids, tags } = await schema.validateAsync(req.body);
        const query = req.user.role === 'admin' ? { _id: { $in: ids } } : { _id: { $in: ids }, createdBy: req.user._id };

        const result = await Lead.updateMany(
            query,
            { $addToSet: { tags: { $each: tags } } }
        );

        res.status(200).json({
            status: 'success',
            message: `Tags added to ${result.modifiedCount} leads`
        });
    } catch (err) {
        res.status(400).json({ status: 'error', message: err.message });
    }
});

router.patch('/:id', auth, async (req, res) => {
    const schema = joi.object({
        name: joi.string(),
        phone: joi.string(),
        fields: joi.array().items(joi.object({
            name: joi.string().required(),
            value: joi.any()
        })),
        tags: joi.array().items(joi.string())
    });

    try {
        const data = await schema.validateAsync(req.body);
        const query = req.user.isSuperAdmin ? { _id: req.params.id } : { _id: req.params.id, createdBy: req.user._id };
        const lead = await Lead.findOneAndUpdate(
            query,
            data,
            {
                new: true,
                runValidators: true
            }
        );

        if (!lead) {
            return res.status(404).json({
                status: 'error',
                message: 'Lead not found'
            });
        }

        res.status(200).json({
            status: 'success',
            data: { lead }
        });
    } catch (err) {
        res.status(400).json({ status: 'error', message: err.message });
    }
});

router.delete('/bulk', auth, async (req, res) => {
    const schema = joi.object({
        ids: joi.array().items(joi.string().required()).required()
    });

    try {
        const { ids } = await schema.validateAsync(req.body);
        const query = req.user.role === 'admin' ? { _id: { $in: ids } } : { _id: { $in: ids }, createdBy: req.user._id };
        const result = await Lead.deleteMany(query);

        res.status(200).json({
            status: 'success',
            message: `${result.deletedCount} leads deleted successfully`
        });
    } catch (err) {
        res.status(400).json({ status: 'error', message: err.message });
    }
});

module.exports = router;
