const ApiError = require('../utils/ApiError');
const httpStatus = require('../utils/httpStatus');
const User = require('../models/User');

// Get all customers
exports.getAllCustomers = async (req, res) => {
  try {
    const { search = '' } = req.query;
    
    // Build the query
    const query = { role: 'customer' };
    
    // Add search functionality
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } },
        { phone: { $regex: search, $options: 'i' } }
      ];
    }

    // Fetch customers with pagination
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;

    const [customers, total] = await Promise.all([
      User.find(query)
        .select('-password -passwordResetToken -passwordResetExpires -__v')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(limit)
        .lean(),
      User.countDocuments(query)
    ]);

    const totalPages = Math.ceil(total / limit);

    res.status(httpStatus.OK).json({
      success: true,
      message: 'Customers retrieved successfully',
      data: customers,
      pagination: {
        total,
        page,
        limit,
        totalPages,
        hasNextPage: page < totalPages,
        hasPreviousPage: page > 1
      }
    });
  } catch (error) {
    console.error('Error retrieving customers:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Error retrieving customers');
  }
};

// Get a customer by ID
exports.getCustomerById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const customer = await User.findOne({ 
      _id: id,
      role: 'customer' 
    }).select('-password -passwordResetToken -passwordResetExpires -__v');

    if (!customer) {
      throw new ApiError(httpStatus.NOT_FOUND, 'Customer not found');
    }

    res.status(httpStatus.OK).json({
      success: true,
      message: 'Customer retrieved successfully',
      data: customer
    });
  } catch (error) {
    if (error instanceof ApiError) {
      throw error;
    }
    console.error('Error retrieving customer:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Error retrieving customer');
  }
};

// Update customer profile
exports.updateCustomerProfile = async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    const [updatedRowsCount] = await User.update(updateData, {
      where: { 
        id, 
        role: 'customer' 
      }
    });

    if (updatedRowsCount === 0) {
      throw new ApiError(httpStatus.NOT_FOUND, 'Customer not found or no changes made');
    }

    const updatedCustomer = await User.findOne({
      where: { id },
      attributes: { 
        exclude: ['password', 'passwordResetToken', 'passwordResetExpires'] 
      }
    });

    res.status(httpStatus.OK).json({
      success: true,
      message: 'Customer profile updated successfully',
      data: updatedCustomer
    });
  } catch (error) {
    console.error('Error updating customer profile:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Error updating customer profile');
  }
};

// Delete a customer
exports.deleteCustomer = async (req, res) => {
  try {
    const { id } = req.params;

    const deletedRowCount = await User.destroy({
      where: { 
        id, 
        role: 'customer' 
      }
    });

    if (deletedRowCount === 0) {
      throw new ApiError(httpStatus.NOT_FOUND, 'Customer not found');
    }

    res.status(httpStatus.OK).json({
      success: true,
      message: 'Customer deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting customer:', error);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Error deleting customer');
  }
};
