const Customer = require("../../models/admin/customerModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");


const createCustomer = async (req, res) => {
    try {
        const userId = req.user._id;
        const orgId = req.user.orgId;
        // if (!name || !state || !city) {
        //     return errorResponse(res, "Name, State and City are required", 400);
        // }
        const {
            name,
            email,
            // customerNumber,
            phone,
            address,
            // location,
            state,
            city,
            // primaryContactPerson,
            notes,
        } = req.body;

        if (!name) {
            return errorResponse(res, "Customer name and customer number is required", 400);
        }

        const existing = await Customer.findOne({
            orgId,
            phone,
            isDeleted: false,
        });

        if (existing) {
            return errorResponse(
                res,
                "Customer already exists. Please search and reuse.",
                400
            );
        }
        const customer = await Customer.create({
            name,
            email,
            // customerNumber,
            phone,
            address,
            // location,
            state,
            city,
            // primaryContactPerson,
            notes,
            orgId,
            createdBy: userId,
            // updatedBy: userId,
        });

        await logUserAction({
            userId,
            orgId,
            action: "CREATE_CUSTOMER",
            model: "Customer",
            modelId: customer._id,
            req,
        });

        return res.status(201).json({
            success: true,
            message: "Customer created successfully",
            data: customer,
        });
    } catch (err) {
        if (err.code === 11000) {
            return errorResponse(res, "Customer already exists", 400);
        }
        return errorResponse(res, "Failed to create customer", 500, err);
    }
};


const getAllCustomers = async (req, res) => {
    try {
        const orgId = req.user.orgId;
        const { search, page = 1, limit = 10, isActive } = req.query;

        const filter = {
            orgId,
            isDeleted: false,
        };

        if (isActive !== undefined) {
            filter.isActive = isActive === "true";
        }

        if (search) {
            filter.$or = [
                { name: { $regex: search, $options: "i" } },
                { customerNumber: { $regex: search, $options: "i" } },
                { phone: { $regex: search, $options: "i" } },
                { email: { $regex: search, $options: "i" } },
            ];
        }

        const skip = (page - 1) * limit;

        const [customers, total] = await Promise.all([
            Customer.find(filter)
                .sort({ createdAt: -1 })
                .populate("updatedBy", "firstName lastName")
                .skip(skip)
                .limit(Number(limit)),
            Customer.countDocuments(filter),
        ]);

        return res.json({
            success: true,
            data: customers,
            pagination: {
                total,
                page: Number(page),
                limit: Number(limit),
                pages: Math.ceil(total / limit),
            },
        });
    } catch (err) {
        return errorResponse(res, "Failed to fetch customers", 500, err);
    }
};

const getCustomerById = async (req, res) => {
    try {
        const customer = await Customer.findOne({
            _id: req.params.id,
            orgId: req.user.orgId,
            isDeleted: false,
        });

        if (!customer) {
            return errorResponse(res, "Customer not found", 404);
        }

        return res.json({
            success: true,
            data: customer,
        });
    } catch (err) {
        return errorResponse(res, "Failed to fetch customer", 500, err);
    }
};


const updateCustomer = async (req, res) => {
    try {
        const customer = await Customer.findOne({
            _id: req.params.id,
            orgId: req.user.orgId,
            isDeleted: false,
        });

        if (!customer) {
            return errorResponse(res, "Customer not found", 404);
        }

        Object.assign(customer, req.body, {
            updatedBy: req.user._id,
        });

        await customer.save();

        await logUserAction({
            userId: req.user._id,
            orgId: req.user.orgId,
            action: "UPDATE_CUSTOMER",
            model: "Customer",
            modelId: customer._id,
            req,
        });

        return res.json({
            success: true,
            message: "Customer updated successfully",
            data: customer,
        });
    } catch (err) {
        return errorResponse(res, "Failed to update customer", 500, err);
    }
};

const deleteCustomer = async (req, res) => {
    try {
        const customer = await Customer.findOne({
            _id: req.params.id,
            orgId: req.user.orgId,
            isDeleted: false,
        });

        if (!customer) {
            return errorResponse(res, "Customer not found", 404);
        }

        customer.isDeleted = true;
        customer.updatedBy = req.user._id;

        await customer.save();

        await logUserAction({
            userId: req.user._id,
            orgId: req.user.orgId,
            action: "DELETE_CUSTOMER",
            model: "Customer",
            modelId: customer._id,
            req,
        });

        return res.json({
            success: true,
            message: "Customer deleted successfully",
        });
    } catch (err) {
        return errorResponse(res, "Failed to delete customer", 500, err);
    }
};

module.exports = {
    createCustomer,
    getAllCustomers,
    getCustomerById,
    updateCustomer,
    deleteCustomer,
};
