import { CustomerModel, customerValidationSchema } from "../models/customer";
import { Request, Response } from "express";
import { Op } from "sequelize";

/// Create new customer
export const createCustomer = async (req: Request, res: Response) => {
  const { error } = customerValidationSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });

  try {
    // Check if email already exists
    const existingCustomer = await CustomerModel.findOne({
      where: { emailAddress: req.body.emailAddress },
    });
    if (existingCustomer)
      return res.status(400).json({ error: "Email address already exists." });

    const newCustomer = await CustomerModel.create(req.body);
    return res
      .status(200)
      .json({ message: "Customer created successfully.", id: newCustomer.id });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Get all customers
export const getAllCustomers = async (req: Request, res: Response) => {
  try {
    const customers = await CustomerModel.findAll({
      where: { isDeleted: false },
    });
    return res.status(200).json(customers);
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Update existing customer
export const updateCustomer = async (req: Request, res: Response) => {
  try {
    // Find the customer by ID
    const customer = await CustomerModel.findByPk(req.params.id);
    if (!customer)
      return res.status(404).json({ error: "Customer not found." });

    // Check if updating email and it already exists
    if (req.body.emailAddress) {
      const existingCustomer = await CustomerModel.findOne({
        where: {
          emailAddress: req.body.emailAddress,
          id: { [Op.ne]: req.params.id },
        },
      });
      if (existingCustomer)
        return res.status(400).json({ error: "Email address already exists." });
    }

    // Validate the request body
    const { error } = customerValidationSchema.validate(req.body);
    if (error) return res.status(400).json({ error: error.details[0].message });

    // Update the customer details
    await customer.update(req.body);

    // Send success response
    return res
      .status(200)
      .json({ message: "Customer updated successfully.", id: customer.id });
  } catch (ex) {
    console.error(`Error updating customer: ${ex}`);
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Delete a customer
export const deleteCustomer = async (req: Request, res: Response) => {
  try {
    // Find the customer by ID
    const customer = await CustomerModel.findByPk(req.params.id);
    if (!customer)
      return res.status(404).json({ error: "Customer not found." });

    // Soft delete the customer
    await customer.update({ isDeleted: true });

    // Send success response
    return res.status(200).json({ message: "Customer deleted successfully." });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};
