import { supabase } from './supabase'

// ============================================
// UPLOAD FUNCTIONS
// ============================================

export const uploadLogo = async (file: File, projectId: string, type: 'empresa' | 'cliente') => {
  const fileName = `${projectId}/${type}-${Date.now()}.${file.name.split('.').pop()}`
  
  const { error } = await supabase.storage
    .from('logos')
    .upload(fileName, file, {
      cacheControl: '3600',
      upsert: false,
    })

  if (error) throw error

  // Obter URL pública
  const { data: publicUrl } = supabase.storage
    .from('logos')
    .getPublicUrl(fileName)

  return publicUrl.publicUrl
}

export const uploadMarcaAgua = async (file: File, projectId: string) => {
  const fileName = `${projectId}/marca-agua-${Date.now()}.${file.name.split('.').pop()}`
  
  const { error } = await supabase.storage
    .from('marca-agua')
    .upload(fileName, file, {
      cacheControl: '3600',
      upsert: false,
    })

  if (error) throw error

  // Obter URL pública
  const { data: publicUrl } = supabase.storage
    .from('marca-agua')
    .getPublicUrl(fileName)

  return publicUrl.publicUrl
}

export const uploadDocumento = async (file: File, projectId: string) => {
  const fileName = `${projectId}/${Date.now()}-${file.name}`
  
  const { error } = await supabase.storage
    .from('documentos')
    .upload(fileName, file, {
      cacheControl: '3600',
      upsert: false,
    })

  if (error) throw error

  // Obter URL pública
  const { data: publicUrl } = supabase.storage
    .from('documentos')
    .getPublicUrl(fileName)

  return publicUrl.publicUrl
}

export const deleteFile = async (bucket: string, filePath: string) => {
  const { error } = await supabase.storage
    .from(bucket)
    .remove([filePath])

  if (error) throw error
}
