START TRANSACTION;

DELETE FROM stock_depot;

INSERT INTO stock_depot (produit_id, depot_id, quantite)
SELECT
    produit_id,
    depot_id,
    SUM(qty) AS quantite
FROM (
    -- Entrées
    SELECT
        produit_id,
        depot_dest_id AS depot_id,
        quantite AS qty
    FROM mouvements_stock
    WHERE depot_dest_id IS NOT NULL

    UNION ALL

    -- Sorties
    SELECT
        produit_id,
        depot_source_id AS depot_id,
        -quantite AS qty
    FROM mouvements_stock
    WHERE depot_source_id IS NOT NULL

    UNION ALL

    -- Cas stock global (sans dépôt)
    SELECT
        produit_id,
        NULL AS depot_id,
        quantite AS qty
    FROM mouvements_stock
    WHERE depot_dest_id IS NULL
      AND depot_source_id IS NULL
) x
GROUP BY produit_id, depot_id;

COMMIT;
