import { Request, Response } from 'express';
import { Company } from '../models/Company';

export const getCompanies = async (req: Request, res: Response): Promise<void> => {
    try {
        // Fetch all companies (or filter by status if provided)
        // Default: return all companies for management purposes
        const status = req.query.status as string | undefined;
        const query = status ? { status } : {};
        const companies = await Company.find(query).sort({ name: 1 }).lean();
        res.json({ success: true, data: companies });
    } catch (error: any) {
        res.status(500).json({ success: false, message: error.message });
    }
};

export const createCompany = async (req: Request, res: Response): Promise<void> => {
    try {
        const { name, code, taxCode, address, email, phone, status } = req.body;

        if (!name || !code) {
            res.status(400).json({ success: false, message: 'Tên công ty và mã công ty là bắt buộc' });
            return;
        }

        // Check if code already exists
        const existingCompany = await Company.findOne({ code: code.toUpperCase() });
        if (existingCompany) {
            res.status(400).json({ success: false, message: 'Mã công ty đã tồn tại' });
            return;
        }

        const newCompany = await Company.create({
            name,
            code: code.toUpperCase(),
            taxCode,
            address,
            email,
            phone,
            status: status || 'active'
        });

        res.status(201).json({ success: true, data: newCompany });
    } catch (error: any) {
        res.status(500).json({ success: false, message: error.message });
    }
};

export const updateCompany = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const { name, code, taxCode, address, email, phone, status } = req.body;

        const company = await Company.findById(id);
        if (!company) {
            res.status(404).json({ success: false, message: 'Không tìm thấy công ty' });
            return;
        }

        // Check if code is being changed and if it already exists
        if (code && code.toUpperCase() !== company.code) {
            const existingCompany = await Company.findOne({ code: code.toUpperCase() });
            if (existingCompany) {
                res.status(400).json({ success: false, message: 'Mã công ty đã tồn tại' });
                return;
            }
        }

        if (name) company.name = name;
        if (code) company.code = code.toUpperCase();
        if (taxCode !== undefined) company.taxCode = taxCode;
        if (address !== undefined) company.address = address;
        if (email !== undefined) company.email = email;
        if (phone !== undefined) company.phone = phone;
        if (status) company.status = status;

        await company.save();

        res.json({ success: true, data: company });
    } catch (error: any) {
        res.status(500).json({ success: false, message: error.message });
    }
};

export const deleteCompany = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;

        const company = await Company.findById(id);
        if (!company) {
            res.status(404).json({ success: false, message: 'Không tìm thấy công ty' });
            return;
        }

        await Company.findByIdAndDelete(id);
        res.json({ success: true, message: 'Đã xóa công ty thành công' });
    } catch (error: any) {
        res.status(500).json({ success: false, message: error.message });
    }
};
