import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { createClient as createStorageClient } from '@supabase/supabase-js'

const MAX_FOTOS_POR_TIPO = 3
const MAX_SIZE_MB = 5

// Cliente admin para storage (bypassa RLS por completo)
function adminStorage() {
  return createStorageClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    { auth: { autoRefreshToken: false, persistSession: false } }
  )
}

// GET /api/fotos?cita_id=xxx
export async function GET(req: NextRequest) {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return NextResponse.json({ error: 'No autenticado' }, { status: 401 })

  const citaId = req.nextUrl.searchParams.get('cita_id')
  if (!citaId) return NextResponse.json({ error: 'Falta cita_id' }, { status: 400 })

  // Usar admin para leer sin RLS
  const admin = createAdminClient()
  const { data: fotos, error } = await admin
    .from('fotos_cita')
    .select('*')
    .eq('cita_id', citaId)
    .order('created_at', { ascending: true })

  if (error) return NextResponse.json({ error: error.message }, { status: 500 })
  return NextResponse.json({ fotos })
}

// POST /api/fotos — subir foto (multipart/form-data)
export async function POST(req: NextRequest) {
  // Solo usamos el cliente de usuario para obtener la sesión
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return NextResponse.json({ error: 'No autenticado' }, { status: 401 })

  const formData = await req.formData()
  const file   = formData.get('file') as File | null
  const citaId = formData.get('cita_id') as string
  const tipo   = formData.get('tipo') as 'antes' | 'despues'

  if (!file || !citaId || !tipo) {
    return NextResponse.json({ error: 'Faltan campos requeridos' }, { status: 400 })
  }
  if (file.size > MAX_SIZE_MB * 1024 * 1024) {
    return NextResponse.json({ error: `Máximo ${MAX_SIZE_MB}MB por imagen` }, { status: 400 })
  }
  if (!file.type.startsWith('image/')) {
    return NextResponse.json({ error: 'Solo se permiten imágenes' }, { status: 400 })
  }

  const admin = createAdminClient()

  // Verificar que la cita existe (sin filtro de cliente — la API verifica autenticación)
  const { data: cita, error: citaErr } = await admin
    .from('citas')
    .select('id, cliente_id')
    .eq('id', citaId)
    .single()

  if (citaErr || !cita) {
    return NextResponse.json({ error: `Cita no encontrada` }, { status: 404 })
  }

  // Verificar límite de fotos por tipo
  const { count } = await admin
    .from('fotos_cita')
    .select('*', { count: 'exact', head: true })
    .eq('cita_id', citaId)
    .eq('tipo', tipo)

  if ((count ?? 0) >= MAX_FOTOS_POR_TIPO) {
    return NextResponse.json({ error: `Máximo ${MAX_FOTOS_POR_TIPO} fotos por tipo` }, { status: 400 })
  }

  // Subir a Storage con admin (bypassa políticas de storage)
  const ext = (file.name.split('.').pop() ?? 'jpg').toLowerCase()
  const storagePath = `${user.id}/${citaId}/${tipo}-${Date.now()}.${ext}`
  const buffer = await file.arrayBuffer()

  const storage = adminStorage()

  // Asegurar que el bucket existe
  const { data: buckets } = await storage.storage.listBuckets()
  if (!buckets?.some(b => b.id === 'fotos-citas')) {
    await storage.storage.createBucket('fotos-citas', {
      public: true,
      fileSizeLimit: 10 * 1024 * 1024,
    })
  }

  const { error: uploadError } = await storage.storage
    .from('fotos-citas')
    .upload(storagePath, buffer, { contentType: file.type, upsert: false })

  if (uploadError) {
    console.error('Upload error:', uploadError.message)
    return NextResponse.json({ error: 'Error al subir imagen: ' + uploadError.message }, { status: 500 })
  }

  // URL pública
  const { data: { publicUrl } } = storage.storage
    .from('fotos-citas')
    .getPublicUrl(storagePath)

  // Guardar en BD
  const { data: foto, error: dbError } = await admin
    .from('fotos_cita')
    .insert({
      cita_id: citaId,
      cliente_id: user.id,
      tipo,
      url: publicUrl,
      storage_path: storagePath,
    })
    .select()
    .single()

  if (dbError) {
    await storage.storage.from('fotos-citas').remove([storagePath])
    console.error('DB error:', dbError.message)
    return NextResponse.json({ error: dbError.message }, { status: 500 })
  }

  return NextResponse.json({ foto }, { status: 201 })
}

// DELETE /api/fotos?id=xxx
export async function DELETE(req: NextRequest) {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return NextResponse.json({ error: 'No autenticado' }, { status: 401 })

  const fotoId = req.nextUrl.searchParams.get('id')
  if (!fotoId) return NextResponse.json({ error: 'Falta id' }, { status: 400 })

  const admin = createAdminClient()

  const { data: foto } = await admin
    .from('fotos_cita')
    .select('*')
    .eq('id', fotoId)
    .eq('cliente_id', user.id)
    .single()

  if (!foto) return NextResponse.json({ error: 'Foto no encontrada' }, { status: 404 })

  const storage = adminStorage()
  await storage.storage.from('fotos-citas').remove([foto.storage_path])
  await admin.from('fotos_cita').delete().eq('id', fotoId)

  return NextResponse.json({ ok: true })
}
