-- ============================================================
-- Fotos antes/después por cita
-- ============================================================

CREATE TABLE public.fotos_cita (
  id          UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  cita_id     UUID NOT NULL REFERENCES public.citas(id) ON DELETE CASCADE,
  cliente_id  UUID NOT NULL REFERENCES public.perfiles(id) ON DELETE CASCADE,
  tipo        TEXT NOT NULL CHECK (tipo IN ('antes', 'despues')),
  url         TEXT NOT NULL,
  storage_path TEXT NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_fotos_cita      ON public.fotos_cita(cita_id);
CREATE INDEX idx_fotos_cliente   ON public.fotos_cita(cliente_id);

ALTER TABLE public.fotos_cita ENABLE ROW LEVEL SECURITY;

-- El cliente solo ve y sube sus propias fotos; admin ve todas
CREATE POLICY "fotos_select" ON public.fotos_cita
  FOR SELECT USING (
    auth.uid() = cliente_id OR
    EXISTS (SELECT 1 FROM public.perfiles WHERE id = auth.uid() AND rol = 'admin')
  );

CREATE POLICY "fotos_insert" ON public.fotos_cita
  FOR INSERT WITH CHECK (auth.uid() = cliente_id);

CREATE POLICY "fotos_delete" ON public.fotos_cita
  FOR DELETE USING (
    auth.uid() = cliente_id OR
    EXISTS (SELECT 1 FROM public.perfiles WHERE id = auth.uid() AND rol = 'admin')
  );

-- ============================================================
-- Storage bucket (ejecutar también en Storage → New bucket)
-- O via SQL:
-- ============================================================
INSERT INTO storage.buckets (id, name, public)
VALUES ('fotos-citas', 'fotos-citas', true)
ON CONFLICT (id) DO NOTHING;

-- Política de storage: solo el dueño puede subir
CREATE POLICY "storage_upload" ON storage.objects
  FOR INSERT WITH CHECK (
    bucket_id = 'fotos-citas' AND
    auth.uid()::text = (storage.foldername(name))[1]
  );

CREATE POLICY "storage_select" ON storage.objects
  FOR SELECT USING (bucket_id = 'fotos-citas');

CREATE POLICY "storage_delete" ON storage.objects
  FOR DELETE USING (
    bucket_id = 'fotos-citas' AND
    auth.uid()::text = (storage.foldername(name))[1]
  );
