-- Fix permissions and RLS for ml_shops to make it searchable
-- Run this in Supabase SQL Editor

-- 1. Grant access to postgres/anon/authenticated roles (Standard Supabase setup)
GRANT SELECT ON public.ml_shops TO anon, authenticated, service_role;

-- 2. Enable RLS
ALTER TABLE public.ml_shops ENABLE ROW LEVEL SECURITY;

-- 3. Create policies
-- Drop existing potential policies to avoid conflicts
DROP POLICY IF EXISTS "Public can view active shops" ON public.ml_shops;
DROP POLICY IF EXISTS "Merchants can view own shop" ON public.ml_shops;

-- Policy: Everyone can see active shops
CREATE POLICY "Public can view active shops"
ON public.ml_shops
FOR SELECT
USING (status = 1);

-- Policy: Merchants can see and edit their own shop
CREATE POLICY "Merchants can view own shop"
ON public.ml_shops
FOR ALL
USING (auth.uid() = merchant_id);

-- 4. Update product_count for the test shop (and others)
-- This ensures the sorting works as expected
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
);
