-- Migration: companies and partners tables with relationships

-- 1. Create companies table
CREATE TABLE IF NOT EXISTS public.companies (
  id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name       TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- 2. Create partners table with optional company reference
CREATE TABLE IF NOT EXISTS public.partners (
  id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name       TEXT NOT NULL,
  company_id UUID REFERENCES public.companies(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Enable RLS on both tables
ALTER TABLE public.companies ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.partners ENABLE ROW LEVEL SECURITY;

-- Policies for companies
DROP POLICY IF EXISTS "Admins und Unternehmen lesen" ON public.companies;
CREATE POLICY "Admins und Unternehmen lesen"
  ON public.companies FOR SELECT
  USING (auth.role() = 'authenticated');

DROP POLICY IF EXISTS "Service role kann alles Unternehmen" ON public.companies;
CREATE POLICY "Service role kann alles Unternehmen"
  ON public.companies FOR ALL
  USING (true)
  WITH CHECK (true);

-- Policies for partners
DROP POLICY IF EXISTS "Admins und Partner lesen" ON public.partners;
CREATE POLICY "Admins und Partner lesen"
  ON public.partners FOR SELECT
  USING (auth.role() = 'authenticated');

DROP POLICY IF EXISTS "Service role kann alles Partner" ON public.partners;
CREATE POLICY "Service role kann alles Partner"
  ON public.partners FOR ALL
  USING (true)
  WITH CHECK (true);

-- 3. Add company_id to users (instead of partner_id)
ALTER TABLE public.users
  ADD COLUMN IF NOT EXISTS company_id UUID REFERENCES public.companies(id) ON DELETE SET NULL;

-- Reload schema cache
NOTIFY pgrst, 'reload schema';
