import { Request, Response } from "express";
import {
  SizeDefinationModel,
  sizeDefinationSchema,
} from "../models/size_defination";
import _, { size } from "lodash";
import { Op } from "sequelize";

/// Create a new size definition
const createSizeDefination = async (req: Request, res: Response) => {
  // 1. Validate the request body
  const { error } = sizeDefinationSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });

  try {
    // 2. Check if a size with this number already exists
    let sizeDef = await SizeDefinationModel.findOne({
      where: { sizeNumber: req.body.sizeNumber, gender: req.body.gender },
    });
    if (sizeDef)
      return res.status(400).json({ error: "Size number already exists." });

    // 3. Create and save the new size definition
    sizeDef = new SizeDefinationModel(req.body);
    await sizeDef.save();

    // 4. Send success response
    res.status(200).json({
      message: "Size definition created successfully.",
      id: sizeDef.id,
    });
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Get all size definitions
const getAllSizeDefinations = async (req: Request, res: Response) => {
  try {
    const sizeDefinitions = await SizeDefinationModel.findAll();
    const response = sizeDefinitions.map((item) => {
      return {
        ...item.toJSON(),
        upperWear: JSON.parse(item.upperWear.toString()),
        lowerWear: JSON.parse(item.lowerWear.toString()),
        headCover: item.headCover
          ? JSON.parse(item.headCover.toString())
          : null,
      };
    });
    res.status(200).json(response);
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Get a single size definition by ID
const getSizeDefinationById = async (req: Request, res: Response) => {
  try {
    const sizeDefinition = await SizeDefinationModel.findByPk(req.params.id);

    if (!sizeDefinition)
      return res.status(404).json({ error: "Size definition not found." });

    res.status(200).json(sizeDefinition);
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Delete size definition by ID
const deleteSizeById = async (req: Request, res: Response) => {
  const deleteCount = await SizeDefinationModel.destroy({
    where: { id: req.params.id },
  });
  if (deleteCount === 0)
    return res.status(400).json({ Error: "Size not found" });

  return res.status(200).json({ message: "Size deleted successfully" });
};

/// Update definition
const updateDefinition = async (req: Request, res: Response) => {
  const sizeDef = await SizeDefinationModel.findByPk(req.params.id);
  if (!sizeDef)
    return res.status(400).json({ Error: "No definittion found of this ID" });

  // Check if another record (not the current one) has the same sizeNumber and gender
  const findData = await SizeDefinationModel.findOne({
    where: { 
      sizeNumber: req.body.sizeNumber, 
      gender: req.body.gender,
      id: { [Op.ne]: req.params.id } // ✅ Exclude current record
    },
  });
  if (findData) return res.status(400).json({ error: "Size already exits" });
  
  await sizeDef.update(req.body);
  return res.status(200).json({ message: "Size definition updated successfully" });
};

export {
  createSizeDefination,
  getAllSizeDefinations,
  getSizeDefinationById,
  deleteSizeById,
  updateDefinition,
};
