import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { cancelarEventoCalendario } from '@/lib/google-calendar/slots'

// PATCH /api/citas/[id] — Actualizar estado de una cita
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const supabase = await createClient()
    const { data: { user } } = await supabase.auth.getUser()

    if (!user) {
      return NextResponse.json({ error: 'No autenticado' }, { status: 401 })
    }

    const body = await req.json()
    const { estado, notas } = body

    const adminClient = createAdminClient()

    // Obtener la cita actual
    const { data: cita } = await adminClient
      .from('citas')
      .select('*, perfil:perfiles(rol)')
      .eq('id', id)
      .single()

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

    // Verificar permisos
    const { data: perfil } = await supabase
      .from('perfiles')
      .select('rol')
      .eq('id', user.id)
      .single()

    const esAdmin = perfil?.rol === 'admin' || perfil?.rol === 'barbero'
    const esPropio = cita.cliente_id === user.id

    if (!esAdmin && !esPropio) {
      return NextResponse.json({ error: 'Sin permisos' }, { status: 403 })
    }

    // Si se cancela, eliminar el evento de Google Calendar
    if (estado === 'cancelada' && cita.google_event_id) {
      try {
        await cancelarEventoCalendario(cita.google_event_id)
      } catch (err) {
        console.error('Error eliminando evento de Calendar:', err)
      }
    }

    const { data: citaActualizada, error } = await adminClient
      .from('citas')
      .update({ estado, notas, google_event_id: estado === 'cancelada' ? null : cita.google_event_id })
      .eq('id', id)
      .select()
      .single()

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

    return NextResponse.json({ cita: citaActualizada })
  } catch (err) {
    console.error(err)
    return NextResponse.json({ error: 'Error interno del servidor' }, { status: 500 })
  }
}
