-- ============================================================
-- PASO 1: Crear tabla fotos_cita
-- ============================================================
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS idx_fotos_cita    ON public.fotos_cita(cita_id);
CREATE INDEX IF NOT EXISTS idx_fotos_cliente ON public.fotos_cita(cliente_id);

ALTER TABLE public.fotos_cita ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "fotos_select" ON public.fotos_cita;
DROP POLICY IF EXISTS "fotos_insert" ON public.fotos_cita;
DROP POLICY IF EXISTS "fotos_delete" ON public.fotos_cita;

CREATE POLICY "fotos_select" ON public.fotos_cita
  FOR SELECT USING (true);

CREATE POLICY "fotos_insert" ON public.fotos_cita
  FOR INSERT WITH CHECK (true);

CREATE POLICY "fotos_delete" ON public.fotos_cita
  FOR DELETE USING (true);

-- ============================================================
-- PASO 2: Crear bucket de storage (si no existe)
-- ============================================================
INSERT INTO storage.buckets (id, name, public, file_size_limit)
VALUES ('fotos-citas', 'fotos-citas', true, 10485760)
ON CONFLICT (id) DO NOTHING;

-- Políticas de storage abiertas (el control está en la API)
DROP POLICY IF EXISTS "storage_upload" ON storage.objects;
DROP POLICY IF EXISTS "storage_select" ON storage.objects;
DROP POLICY IF EXISTS "storage_delete" ON storage.objects;

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

CREATE POLICY "storage_upload" ON storage.objects
  FOR INSERT WITH CHECK (bucket_id = 'fotos-citas');

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

-- ============================================================
-- PASO 3: Corregir perfil duplicado — asignar rol admin
-- al usuario que tiene las citas agendadas
-- ============================================================
UPDATE public.perfiles
SET rol = 'admin'
WHERE id = 'a3c15f50-21bb-4d60-a2ea-8fbe8d5f7fcf';
