-- 1. Immediate Fix: Update all shop counts based on existing products
-- Recalculate based on merchant_id link
UPDATE public.ml_shops s
SET product_count = (
    SELECT count(*) 
    FROM public.ml_products p 
    WHERE p.merchant_id = s.merchant_id 
    AND p.status = 1
);

-- 2. Permanent Fix: Create a Trigger to keep it updated automatically
-- This ensures when you add/remove products in the future, the shop count updates

CREATE OR REPLACE FUNCTION public.update_shop_product_count_trigger()
RETURNS TRIGGER AS $$
BEGIN
    -- Update count for the merchant associated with the NEW product (on Insert/Update)
    IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
        UPDATE public.ml_shops
        SET product_count = (
            SELECT count(*) 
            FROM public.ml_products 
            WHERE merchant_id = NEW.merchant_id 
            AND status = 1
        )
        WHERE merchant_id = NEW.merchant_id;
    END IF;

    -- Update count for the merchant associated with the OLD product (on Delete/Update)
    IF (TG_OP = 'DELETE' OR (TG_OP = 'UPDATE' AND OLD.merchant_id IS DISTINCT FROM NEW.merchant_id)) THEN
        UPDATE public.ml_shops
        SET product_count = (
            SELECT count(*) 
            FROM public.ml_products 
            WHERE merchant_id = OLD.merchant_id 
            AND status = 1
        )
        WHERE merchant_id = OLD.merchant_id;
    END IF;

    RETURN NULL;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Drop trigger if exists to avoid error on multiple runs
DROP TRIGGER IF EXISTS on_product_change_update_shop_count ON public.ml_products;

-- Create the trigger
CREATE TRIGGER on_product_change_update_shop_count
AFTER INSERT OR UPDATE OR DELETE ON public.ml_products
FOR EACH ROW
EXECUTE FUNCTION public.update_shop_product_count_trigger();
