import { ProductModel, productValidationSchema } from "../models/product";
import { Request, Response } from "express";

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

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

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

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

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

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

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

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

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

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