-- ═══════════════════════════════════════════════════════════════════════════
-- Storage bucket para imagens do Agendador Online
-- Execute no Supabase SQL Editor
-- ═══════════════════════════════════════════════════════════════════════════

-- ── 1. Criar o bucket ──────────────────────────────────────────────────────
INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
VALUES (
  'agendador',
  'agendador',
  true,                          -- público (URLs diretas sem assinar)
  5242880,                       -- 5 MB
  ARRAY['image/jpeg','image/png','image/webp','image/gif']
)
ON CONFLICT (id) DO UPDATE
  SET public            = true,
      file_size_limit   = 5242880,
      allowed_mime_types = ARRAY['image/jpeg','image/png','image/webp','image/gif'];

-- ── 2. Políticas ───────────────────────────────────────────────────────────

-- Leitura pública (anon e authenticated)
DROP POLICY IF EXISTS "agendador_storage_public_read" ON storage.objects;
CREATE POLICY "agendador_storage_public_read"
  ON storage.objects FOR SELECT
  USING (bucket_id = 'agendador');

-- Upload: apenas o dono da pasta (owner_id é o primeiro segmento do path)
DROP POLICY IF EXISTS "agendador_storage_owner_insert" ON storage.objects;
CREATE POLICY "agendador_storage_owner_insert"
  ON storage.objects FOR INSERT
  TO authenticated
  WITH CHECK (
    bucket_id = 'agendador'
    AND (storage.foldername(name))[1] = auth.uid()::text
  );

-- Update/upsert pelo dono
DROP POLICY IF EXISTS "agendador_storage_owner_update" ON storage.objects;
CREATE POLICY "agendador_storage_owner_update"
  ON storage.objects FOR UPDATE
  TO authenticated
  USING (
    bucket_id = 'agendador'
    AND (storage.foldername(name))[1] = auth.uid()::text
  );

-- Delete pelo dono
DROP POLICY IF EXISTS "agendador_storage_owner_delete" ON storage.objects;
CREATE POLICY "agendador_storage_owner_delete"
  ON storage.objects FOR DELETE
  TO authenticated
  USING (
    bucket_id = 'agendador'
    AND (storage.foldername(name))[1] = auth.uid()::text
  );
