"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteProduct = exports.updateProduct = exports.getAllProducts = exports.createProduct = void 0;
const product_1 = require("../models/product");
/// Create new product
const createProduct = async (req, res) => {
    const { error } = product_1.productValidationSchema.validate(req.body);
    if (error)
        return res.status(400).json({ error: error.details[0].message });
    try {
        const newProduct = await product_1.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." });
    }
};
exports.createProduct = createProduct;
/// Get all products
const getAllProducts = async (req, res) => {
    try {
        const products = await product_1.ProductModel.findAll({
            where: { isDeleted: false },
        });
        return res.status(200).json(products);
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.getAllProducts = getAllProducts;
/// Update existing product
const updateProduct = async (req, res) => {
    try {
        // Find the product by ID
        const product = await product_1.ProductModel.findByPk(req.params.id);
        if (!product)
            return res.status(404).json({ error: "Product not found." });
        // Validate the request body
        const { error } = product_1.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." });
    }
};
exports.updateProduct = updateProduct;
/// Delete a product
const deleteProduct = async (req, res) => {
    try {
        // Find the product by ID
        const product = await product_1.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." });
    }
};
exports.deleteProduct = deleteProduct;
