-- =============================================================================
-- CONFIGURAÇÃO DO STORAGE PARA MENSAGENS
-- Execute este arquivo no SQL Editor do Supabase Dashboard
-- Project: etblfypcxxtvvuqjkrgd
-- =============================================================================

-- Remover políticas existentes (se houver)
DROP POLICY IF EXISTS "Users can upload files" ON storage.objects;
DROP POLICY IF EXISTS "Anyone can download files" ON storage.objects;
DROP POLICY IF EXISTS "Users can update their own files" ON storage.objects;
DROP POLICY IF EXISTS "Users can delete their own files" ON storage.objects;

-- Política 1: Upload (INSERT)
-- Permite usuários autenticados fazerem upload de arquivos em suas próprias pastas
CREATE POLICY "Users can upload files"
ON storage.objects FOR INSERT
TO authenticated
WITH CHECK (
  bucket_id = 'message-files' AND
  auth.uid()::text = (storage.foldername(name))[1]
);

-- Política 2: Download (SELECT)
-- Permite qualquer pessoa (autenticada ou não) baixar arquivos
CREATE POLICY "Anyone can download files"
ON storage.objects FOR SELECT
TO public
USING (bucket_id = 'message-files');

-- Política 3: Update
-- Permite usuários atualizarem apenas seus próprios arquivos
CREATE POLICY "Users can update their own files"
ON storage.objects FOR UPDATE
TO authenticated
USING (
  bucket_id = 'message-files' AND
  auth.uid()::text = (storage.foldername(name))[1]
);

-- Política 4: Delete
-- Permite usuários deletarem apenas seus próprios arquivos
CREATE POLICY "Users can delete their own files"
ON storage.objects FOR DELETE
TO authenticated
USING (
  bucket_id = 'message-files' AND
  auth.uid()::text = (storage.foldername(name))[1]
);

-- =============================================================================
-- CONFIGURAÇÕES DO BUCKET
-- =============================================================================

-- Definir limite de tamanho de arquivo: 10MB
UPDATE storage.buckets
SET file_size_limit = 10485760
WHERE id = 'message-files';

-- Definir tipos MIME permitidos
UPDATE storage.buckets
SET allowed_mime_types = ARRAY[
  'application/pdf',
  'image/jpeg',
  'image/png',
  'image/gif',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
]
WHERE id = 'message-files';
