import { kappa } from '@/services/kappa-api'
import { saveUser, saveLookup } from '@/services/users-db'
import type { UserRecord } from '@/services/db'

const CONCURRENCY = 5

interface RawUserDetail {
  id: number
  email?: string
  first_name?: string
  last_name?: string
  username?: string
  is_active?: boolean
  is_staff?: boolean
  phone?: string
  position?: string
  role?: number | null
  role_detail?: { id: number; name: string } | null
  employee?: { company?: number | null; company_detail?: { id: number; name: string } | null } | null
  last_login?: string
  date_joined?: string
}

/**
 * Sincroniza detalles de usuarios desde KAPPA.
 * Itera sobre los IDs dados, con límite de concurrencia.
 * Guarda en tablas `users` + `lookups` (roles, companies).
 */
export async function syncUserDetails(userIds: number[], onProgress?: (done: number, total: number) => void): Promise<{ ok: number; fail: number }> {
  let ok = 0
  let fail = 0
  const total = userIds.length

  // Procesar en lotes concurrentes
  for (let i = 0; i < userIds.length; i += CONCURRENCY) {
    const batch = userIds.slice(i, i + CONCURRENCY)
    const results = await Promise.allSettled(batch.map(id => fetchAndSaveUser(id)))

    for (const r of results) {
      if (r.status === 'fulfilled' && r.value) ok++
      else fail++
    }

    onProgress?.(Math.min(i + CONCURRENCY, total), total)
  }

  console.log(`[UserSync] ${ok} OK, ${fail} fail de ${total}`)
  return { ok, fail }
}

async function fetchAndSaveUser(id: number): Promise<boolean> {
  try {
    const raw = await kappa.getUserDetail(id) as unknown as RawUserDetail
    if (!raw || !raw.id) return false

    const now = new Date().toISOString()

    // Guardar usuario
    const user: UserRecord = {
      id: raw.id,
      email: raw.email || '',
      firstName: raw.first_name || '',
      lastName: raw.last_name || '',
      fullName: `${raw.first_name || ''} ${raw.last_name || ''}`.trim() || raw.email || '',
      username: raw.username || null,
      isActive: raw.is_active !== undefined ? raw.is_active : true,
      isStaff: raw.is_staff || false,
      roleId: raw.role ?? null,
      cellId: null,
      seniority: null,
      companyId: raw.employee?.company ?? null,
      phone: raw.phone || null,
      position: raw.position || null,
      lastActive: raw.last_login || null,
      createdAt: raw.date_joined || null,
      updatedAt: now,
    }
    await saveUser(user)

    // Guardar lookup de rol
    if (raw.role_detail?.id && raw.role_detail?.name) {
      await saveLookup('role', raw.role_detail.id, raw.role_detail.name)
    }

    // Guardar lookup de compañía
    if (raw.employee?.company_detail?.id && raw.employee?.company_detail?.name) {
      await saveLookup('company', raw.employee.company_detail.id, raw.employee.company_detail.name)
    }

    return true
  } catch (e) {
    console.error(`[UserSync] Error fetching user ${id}:`, e)
    return false
  }
}
