const { catchAsyncErrors } = require("../../middlewares/catchAsyncErrors");
const ErrorHandler = require("../../utils/ErrorHandler");
const Staff = require("../../models/staff.model");

// Create Staff for Zone Admin
exports.createZoneStaff = catchAsyncErrors(async (req, res, next) => {
    const { fullName, email, password, phone, permissions } = req.body;

    if (!fullName || !email || !password || !phone) {
        return next(new ErrorHandler("Please provide all required fields", 400));
    }

    // Check if staff exists in any collection (similar to user check) or just Staff
    // Check if staff exists in any collection
    const findUserInAllCollections = require("../../helper/FindUserInAllCollections");
    const { user: existingUser } = await findUserInAllCollections(email);
    if (existingUser) {
        return next(new ErrorHandler("User with this email already exists across the platform", 400));
    }

    const { user: existingPhone } = await findUserInAllCollections(phone);
    if (existingPhone) {
        return next(new ErrorHandler("User with this phone already exists across the platform", 400));
    }

    // Filter permissions to ensure Zone Admin only assigns allowed permissions
    // For now, allowing all permissions relevant to Zone Admin panel.
    // In future, we can validate against a whitelist.

    const staff = await Staff.create({
        fullName,
        email,
        password,
        phone,
        permissions, // Array of permission strings
        createdBy: req.user._id,
        role: 'staff',
        ownerType: 'ZoneAdmin' // Crucial: owned by Zone Admin
    });

    res.status(201).json({
        success: true,
        message: "Staff member created successfully",
        staff
    });
});

// Get All Zone Staff
exports.getAllZoneStaff = catchAsyncErrors(async (req, res, next) => {
    // Only return staff created by THIS Zone Admin
    const staffMembers = await Staff.find({ createdBy: req.user._id }).sort({ createdAt: -1 });

    res.status(200).json({
        success: true,
        count: staffMembers.length,
        staff: staffMembers
    });
});

// Get Zone Staff By ID
exports.getZoneStaffById = catchAsyncErrors(async (req, res, next) => {
    const staff = await Staff.findOne({ _id: req.params.id, createdBy: req.user._id });

    if (!staff) {
        return next(new ErrorHandler("Staff member not found or access denied", 404));
    }

    res.status(200).json({
        success: true,
        staff
    });
});

// Update Zone Staff
exports.updateZoneStaff = catchAsyncErrors(async (req, res, next) => {
    const { fullName, email, phone, permissions, status } = req.body;

    // Ensure staff belongs to this Zone Admin
    let staff = await Staff.findOne({ _id: req.params.id, createdBy: req.user._id });

    if (!staff) {
        return next(new ErrorHandler("Staff member not found or access denied", 404));
    }

    // Update fields
    if (fullName) staff.fullName = fullName;
    if (email) staff.email = email;
    if (phone) staff.phone = phone;
    if (permissions) staff.permissions = permissions;
    if (status) staff.status = status;

    // Check if password update is requested
    if (req.body.password) {
        staff.password = req.body.password;
    }

    await staff.save();

    res.status(200).json({
        success: true,
        message: "Staff member updated successfully",
        staff
    });
});

// Delete Zone Staff
exports.deleteZoneStaff = catchAsyncErrors(async (req, res, next) => {
    const staff = await Staff.findOne({ _id: req.params.id, createdBy: req.user._id });

    if (!staff) {
        return next(new ErrorHandler("Staff member not found or access denied", 404));
    }

    await Staff.findByIdAndDelete(req.params.id);

    res.status(200).json({
        success: true,
        message: "Staff member deleted successfully"
    });
});
