-- Migration: Update end_customers.partner_id to reference public.companies.id
-- and update RLS policies accordingly.

-- 1. Drop old foreign key constraint if exists
ALTER TABLE public.end_customers
  DROP CONSTRAINT IF EXISTS end_customers_partner_id_fkey;

-- 2. Add new foreign key constraint to public.companies(id)
-- Note: the column is still called partner_id, but references companies now.
ALTER TABLE public.end_customers
  ADD CONSTRAINT end_customers_partner_id_fkey
  FOREIGN KEY (partner_id)
  REFERENCES public.companies(id)
  ON DELETE CASCADE;

-- 3. Recreate RLS policies for end_customers
DROP POLICY IF EXISTS "Partner sehen nur eigene Endkunden" ON public.end_customers;
CREATE POLICY "Partner sehen nur eigene Endkunden" ON public.end_customers
  FOR ALL
  USING (
    partner_id = (SELECT company_id FROM public.users WHERE id = auth.uid())
  )
  WITH CHECK (
    partner_id = (SELECT company_id FROM public.users WHERE id = auth.uid())
  );

-- 4. Licenses policy recreation is omitted since licenses table is dropped.

-- Reload Schema Cache
NOTIFY pgrst, 'reload schema';
