-- ============================================================
-- ROLLBACK: Restaurar report_inventoryv2 a su estado original
-- Fecha: 2026-06-09
-- ============================================================
-- Usar este script SOLO si el cambio de ordenamiento causa
-- problemas y se necesita restaurar el comportamiento anterior.
-- ============================================================

DROP FUNCTION IF EXISTS public.report_inventoryv2();

CREATE OR REPLACE FUNCTION public.report_inventoryv2()
    RETURNS TABLE(
        date_movement date,
        id_product integer,
        name_product character varying,
        category_en character varying,
        category_esp character varying,
        movement character varying,
        comments_discard character varying,
        housekepper_name character varying,
        quantity integer,
        average_cost numeric,
        before_stock bigint,
        stock bigint
    )
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000
AS $BODY$
BEGIN
    RETURN QUERY
    SELECT
        sm.date_st_mov AS date_movement,
        p.id_product,
        p.name_product,
        pcat.name_prod_category,
        pcat.spanish_name,
        mt.name_mov_type AS movement,
        sd.reason,
        emp.name_employee,
        /* Cantidad segun el tipo de movimiento */
        CASE
            WHEN mt.name_mov_type = 'Purchase'     THEN sm.quantity
            WHEN mt.name_mov_type = 'Adjustment'   THEN sa.adjustment::int
            WHEN mt.name_mov_type = 'New product'  THEN sm.stock_current::int
            WHEN mt.name_mov_type = 'Discard'      THEN sd.quantity*(-1)
            WHEN mt.name_mov_type = 'Consumption'  THEN sc.consumption_quantity*(-1)
            ELSE NULL
        END AS quantity,
        sm.average_cost,
        sm.stock_before,
        sm.stock_current
    FROM stock_movements sm
    INNER JOIN products p
        ON p.id_product = sm.id_product

    INNER JOIN movement_type mt
        ON sm.id_mov_type = mt.id_mov_type

    INNER JOIN stock st
        ON st.id_product = p.id_product

    INNER JOIN product_category pcat
        ON p.id_prod_category = pcat.id_prod_category

    /* AHORA CORRECTO: JOIN por id_stock_mov */
    LEFT JOIN purchase_detail pd
        ON pd.id_stock_mov = sm.id_sto_mov

    LEFT JOIN stock_adjusments sa
        ON sa.id_stock_mov = sm.id_sto_mov

    LEFT JOIN stock_discard sd
        ON sd.id_stock_mov = sm.id_sto_mov

    LEFT JOIN stock_consumption sc
        ON sc.id_stock_mov = sm.id_sto_mov
    LEFT JOIN employees emp
        ON sc.rfc_employee = emp.rfc_employee

    ORDER BY p.id_product, sm.date_st_mov, sm.id_sto_mov;
END;
$BODY$;

ALTER FUNCTION public.report_inventoryv2()
    OWNER TO postgres;

-- Confirmacion
SELECT 'Funcion report_inventoryv2 restaurada a su estado original' AS resultado;
