import { Response } from 'express';
import { Op } from 'sequelize';
import db from '../../database/models/index.js';
const { Outlet, User, Resignation } = db;
import { AuthRequest } from '../../types/express.types.js';

// Get all outlets for logged-in dealer
export const getOutlets = async (req: AuthRequest, res: Response) => {
    try {
        const where: any = {};
        if (req.user?.role === 'Dealer') {
            where.dealerId = req.user.id;
        }

        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const offset = (page - 1) * limit;

        const { count, rows: outlets } = await Outlet.findAndCountAll({
            where,
            include: [
                {
                    model: User,
                    as: 'dealer',
                    attributes: ['fullName', 'email']
                },
                {
                    model: Resignation,
                    as: 'resignations',
                    required: false,
                    where: {
                        status: { [Op.notIn]: ['Completed', 'Rejected'] }
                    }
                }
            ],
            order: [['createdAt', 'DESC']],
            limit,
            offset
        });

        res.json({
            success: true,
            outlets,
            meta: {
                total: count,
                totalPages: Math.ceil(count / limit),
                currentPage: page,
                limit
            }
        });
    } catch (error) {
        console.error('Get outlets error:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching outlets'
        });
    }
};

// Get specific outlet details
export const getOutletById = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;

        const outlet = await Outlet.findByPk(id, {
            include: [{
                model: User,
                as: 'dealer',
                attributes: ['fullName', 'email', 'mobileNumber']
            }]
        });

        if (!outlet) {
            return res.status(404).json({
                success: false,
                message: 'Outlet not found'
            });
        }

        // Check if dealer can access this outlet
        if (req.user?.role === 'Dealer' && outlet.dealerId !== req.user.id) {
            return res.status(403).json({
                success: false,
                message: 'Access denied'
            });
        }

        res.json({
            success: true,
            outlet
        });
    } catch (error) {
        console.error('Get outlet error:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching outlet'
        });
    }
};

// Create new outlet (admin only)
export const createOutlet = async (req: AuthRequest, res: Response) => {
    try {
        const {
            dealerId,
            code,
            name,
            type,
            address,
            city,
            state,
            pincode,
            establishedDate,
            latitude,
            longitude
        } = req.body;

        // Validate required fields
        if (!dealerId || !code || !name || !type || !address || !city || !state) {
            return res.status(400).json({
                success: false,
                message: 'Missing required fields'
            });
        }

        // Check if code already exists
        const existing = await Outlet.findOne({ where: { code } });
        if (existing) {
            return res.status(400).json({
                success: false,
                message: 'Outlet code already exists'
            });
        }

        const outlet = await Outlet.create({
            dealerId,
            code,
            name,
            type,
            address,
            city,
            state,
            pincode,
            establishedDate,
            latitude,
            longitude,
            status: 'Active'
        });

        res.status(201).json({
            success: true,
            message: 'Outlet created successfully',
            outletId: outlet.id
        });
    } catch (error) {
        console.error('Create outlet error:', error);
        res.status(500).json({
            success: false,
            message: 'Error creating outlet'
        });
    }
};

// Update outlet
export const updateOutlet = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const { name, address, city, state, pincode, status, latitude, longitude } = req.body;

        const outlet = await Outlet.findByPk(id);
        if (!outlet) {
            return res.status(404).json({
                success: false,
                message: 'Outlet not found'
            });
        }

        await outlet.update({
            name: name || outlet.name,
            address: address || outlet.address,
            city: city || outlet.city,
            state: state || outlet.state,
            pincode: pincode || outlet.pincode,
            status: status || outlet.status,
            latitude: latitude || outlet.latitude,
            longitude: longitude || outlet.longitude,
            updatedAt: new Date()
        });

        res.json({
            success: true,
            message: 'Outlet updated successfully'
        });
    } catch (error) {
        console.error('Update outlet error:', error);
        res.status(500).json({
            success: false,
            message: 'Error updating outlet'
        });
    }
};

// Get outlet by code
export const getOutletByCode = async (req: AuthRequest, res: Response) => {
    try {
        const { code } = req.params;
        const outlet = await Outlet.findOne({
            where: { code },
            include: [{
                model: User,
                as: 'dealer',
                attributes: ['fullName', 'email', 'mobileNumber']
            }]
        });

        if (!outlet) {
            return res.status(404).json({
                success: false,
                message: 'Outlet not found'
            });
        }

        res.json({
            success: true,
            outlet
        });
    } catch (error) {
        console.error('Get outlet by code error:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching outlet'
        });
    }
};
