"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deletePurchase = exports.updatePurchase = exports.getAllPurchases = exports.createPurchase = void 0;
const purchase_1 = require("../models/purchase");
/// Create new purchase
const createPurchase = async (req, res) => {
    const { error } = purchase_1.purchaseValidationSchema.validate(req.body);
    if (error)
        return res.status(400).json({ error: error.details[0].message });
    try {
        const newPurchase = await purchase_1.PurchaseModel.create(req.body);
        return res
            .status(200)
            .json({ message: "Purchase created successfully.", id: newPurchase.id });
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.createPurchase = createPurchase;
/// Get all purchases
const getAllPurchases = async (req, res) => {
    try {
        const purchases = await purchase_1.PurchaseModel.findAll({
            where: { isDeleted: false },
        });
        return res.status(200).json(purchases);
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.getAllPurchases = getAllPurchases;
/// Update existing purchase
const updatePurchase = async (req, res) => {
    try {
        // Find the purchase by ID
        const purchase = await purchase_1.PurchaseModel.findByPk(req.params.id);
        if (!purchase)
            return res.status(404).json({ error: "Purchase not found." });
        // Validate the request body
        const { error } = purchase_1.purchaseValidationSchema.validate(req.body);
        if (error)
            return res.status(400).json({ error: error.details[0].message });
        // Update the purchase details
        await purchase.update(req.body);
        // Send success response
        return res
            .status(200)
            .json({ message: "Purchase updated successfully.", id: purchase.id });
    }
    catch (ex) {
        console.error(`Error updating purchase: ${ex}`);
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.updatePurchase = updatePurchase;
/// Delete a purchase
const deletePurchase = async (req, res) => {
    try {
        // Find the purchase by ID
        const purchase = await purchase_1.PurchaseModel.findByPk(req.params.id);
        if (!purchase)
            return res.status(404).json({ error: "Purchase not found." });
        // Soft delete the purchase
        await purchase.update({ isDeleted: true });
        // Send success response
        return res.status(200).json({ message: "Purchase deleted successfully." });
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.deletePurchase = deletePurchase;
