-- Migration: 06_insurance_plan_services_v2
-- Reestrutura insurance_plan_services para ser autônomo (sem FK para services)
-- Adiciona campo name, active e remove service_id

-- Passo 1: remover a tabela antiga se existir e recriar do zero
DROP TABLE IF EXISTS public.insurance_plan_services;

-- Passo 2: criar tabela nova autônoma
CREATE TABLE public.insurance_plan_services (
  id                uuid          DEFAULT gen_random_uuid() NOT NULL,
  insurance_plan_id uuid          NOT NULL,
  name              text          NOT NULL,
  value             numeric(10,2) NOT NULL,
  active            boolean       DEFAULT true NOT NULL,
  created_at        timestamptz   DEFAULT now(),
  updated_at        timestamptz   DEFAULT now(),
  CONSTRAINT insurance_plan_services_pkey PRIMARY KEY (id),
  CONSTRAINT insurance_plan_services_plan_fkey
    FOREIGN KEY (insurance_plan_id) REFERENCES public.insurance_plans(id) ON DELETE CASCADE
);

-- Passo 3: RLS
ALTER TABLE public.insurance_plan_services ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "insurance_plan_services_owner" ON public.insurance_plan_services;
CREATE POLICY "insurance_plan_services_owner"
  ON public.insurance_plan_services
  FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM public.insurance_plans ip
      WHERE ip.id = insurance_plan_services.insurance_plan_id
        AND ip.owner_id = auth.uid()
    )
  )
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.insurance_plans ip
      WHERE ip.id = insurance_plan_services.insurance_plan_id
        AND ip.owner_id = auth.uid()
    )
  );

-- Passo 4: grants
GRANT ALL ON TABLE public.insurance_plan_services TO postgres;
GRANT ALL ON TABLE public.insurance_plan_services TO anon;
GRANT ALL ON TABLE public.insurance_plan_services TO authenticated;
GRANT ALL ON TABLE public.insurance_plan_services TO service_role;

-- Passo 5: trigger updated_at
DROP TRIGGER IF EXISTS set_insurance_plan_services_updated_at ON public.insurance_plan_services;
CREATE TRIGGER set_insurance_plan_services_updated_at
  BEFORE UPDATE ON public.insurance_plan_services
  FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();

-- Passo 6: adicionar campo active na tabela services (se ainda não existir)
ALTER TABLE public.services
  ADD COLUMN IF NOT EXISTS active boolean DEFAULT true NOT NULL;
