-- Corrected triggers for sales invoice items
DROP TRIGGER IF EXISTS `trg_sales_invoice_items_before_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_before_insert` BEFORE INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin
    DECLARE current_stock DECIMAL(10,2);
    DECLARE inventory_id INT;

    SELECT pa.inventoryId INTO inventory_id
    FROM Pos_Accounts pa
    INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
    WHERE si.id = NEW.invoiceId;

    SELECT COALESCE(quantity, 0) INTO current_stock
    FROM Stock_Balance sb
    WHERE productId = NEW.productId AND sb.inventoryId = inventory_id
    LIMIT 1;

    IF NEW.count > current_stock THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Not enough stock to complete sale.';
    END IF;
end;

DROP TRIGGER IF EXISTS `trg_sales_invoice_items_after_insert`;
CREATE DEFINER=`pos`@`%` TRIGGER `trg_sales_invoice_items_after_insert` AFTER INSERT ON `Sales_Invoice_Items` FOR EACH ROW begin DECLARE current_stock DECIMAL(10, 2);

DECLARE inventory_id INT;
DECLARE customer_id INT;
DECLARE pos_id INT;



	INSERT INTO Trigger_Logs (name , message) VALUES ('pos_id', 'init');

    SELECT posAccountId, customerId INTO pos_id, customer_id
    FROM Sales_Invoices si
    WHERE si.id = NEW.invoiceId
    LIMIT 1;
    INSERT INTO Trigger_Logs (name , message) VALUES ('pos_id', pos_id);
    INSERT INTO Trigger_Logs (name , message) VALUES ('customer_id', customer_id);


	SELECT pa.inventoryId INTO inventory_id
	FROM Pos_Accounts pa
	INNER JOIN Sales_Invoices si ON pa.id = si.posAccountId
	WHERE si.id = NEW.invoiceId;



    SELECT COALESCE(quantity, 0) INTO current_stock
    FROM Stock_Balance sb
    WHERE productId = NEW.productId AND sb.inventoryId = inventory_id
    LIMIT 1;

    INSERT INTO Trigger_Logs (name , message) VALUES ('invId', inventory_id);


    INSERT INTO Stock_Movements (
        type,
        quantity,
        fee,
        totalCost,
        referenceType,
        referenceId,
        productId,
        inventoryId,
        avgCost,
        remainedInStock,
        customerId,
        createdAt
    )
    VALUES (
        'OUT',
        NEW.count,
        NEW.fee,
        NEW.total,
        'SALES',
        NEW.invoiceId,
        NEW.productId,
        inventory_id,

        CASE
          WHEN NEW.count = 0 THEN 0
          ELSE NEW.total / NEW.count
        END,
        current_stock - NEW.count,
        customer_id,
        NOW()
    );


END
