export type AdminRole = {
  id: string
  name: string
  description?: string | null
  tenant_id: number | null
}

export type AdminTenant = {
  id: number
  name: string
  short: string
  user_count: number
  locked?: string | null
  lockedByExportJobId?: string | null
}

export type AdminUserProfile = {
  id: string
  user_id: string | null
  tenant_id: number
  full_name: string | null
  first_name: string
  last_name: string
  email?: string | null
  active: boolean
}

export type AdminUser = {
  id: string
  email: string
  display_name: string
  multiTenant: boolean
  must_change_password: boolean
  is_admin: boolean
  profile_defaults: {
    first_name: string
    last_name: string
  }
  tenant_ids: number[]
  role_assignments: { tenant_id: number; role_id: string }[]
  profile_assignments?: { tenant_id: number; profile_id?: string | null }[]
  profiles: AdminUserProfile[]
}

export type AdminOverview = {
  users: AdminUser[]
  tenants: AdminTenant[]
  roles: AdminRole[]
  unassignedProfiles: AdminUserProfile[]
}

export type TenantImportResult = {
  success: boolean
  tenantId: number
  tables: { table: string; rows: number }[]
  files: { restored: number; skipped: number }
  importId?: string
  exportId?: string
  status?: string
  filename?: string
  filesDone?: number
  filesTotal?: number
  error?: string | null
}

export type TenantExportJob = {
  exportId: string
  importId?: string
  tenantId?: number
  operation?: "export" | "import" | string
  status: "queued" | "running" | "ready" | "failed" | string
  filename: string
  fileSize?: number | null
  filesDone?: number
  filesTotal?: number
  error?: string | null
  statusUrl?: string
  downloadUrl?: string | null
  createdAt?: string
  updatedAt?: string | null
  completedAt?: string | null
}

export type SystemStatus = {
  checkedAt: string
  backend: {
    status: string
    uptimeSeconds: number
    nodeVersion: string
    environment: string
  }
  server: {
    status: string
    nodeExporterUrl: string
    error?: string | null
    hostname?: string | null
    kernel?: string | null
    cpuCount?: number | null
    uptimeSeconds?: number | null
    load: { one?: number | null; five?: number | null; fifteen?: number | null }
    memory: { totalBytes?: number | null; availableBytes?: number | null; usedBytes?: number | null; usedPercent?: number | null }
    disk: { rootTotalBytes?: number | null; rootAvailableBytes?: number | null; rootUsedBytes?: number | null; rootUsedPercent?: number | null }
  }
  services: Record<string, {
    ok: boolean
    status: string
    error?: string | null
    [key: string]: any
  }>
}

export type InstanceAgent = {
  id: string
  createdAt: string
  updatedAt: string
  name: string
  description?: string | null
  tokenPrefix: string
  active: boolean
  capabilities: Record<string, any>
  scannerNames: string[]
  printerNames: string[]
  preferredScannerName?: string | null
  scanDefaults: {
    format?: string
    resolution?: number
    mode?: string
    source?: string | null
    [key: string]: any
  }
  lastSeenAt?: string | null
  lastDebugInfo?: Record<string, any> | null
}

export type CreateInstanceAgentResult = {
  agent: InstanceAgent
  token: string
}

export const useAdmin = () => {
  const { $api } = useNuxtApp()

  const getOverview = async (): Promise<AdminOverview> => {
    const response = await $api("/api/admin/overview") as any

    return {
      users: response?.users || [],
      tenants: response?.tenants || [],
      roles: response?.roles || [],
      unassignedProfiles: response?.unassignedProfiles || [],
    }
  }

  const createUser = async (body: Record<string, any>) => {
    return await $api("/api/admin/users", {
      method: "POST",
      body,
    })
  }

  const createUserForProfile = async (profileId: string, body: Record<string, any>) => {
    return await $api(`/api/admin/profiles/${profileId}/create-user`, {
      method: "POST",
      body,
    })
  }

  const updateUser = async (id: string, body: Record<string, any>) => {
    return await $api(`/api/admin/users/${id}`, {
      method: "PUT",
      body,
    })
  }

  const updateUserAccess = async (id: string, body: Record<string, any>) => {
    return await $api(`/api/admin/users/${id}/access`, {
      method: "PUT",
      body,
    })
  }

  const createTenant = async (body: Record<string, any>) => {
    return await $api("/api/admin/tenants", {
      method: "POST",
      body,
    })
  }

  const invitePortalUser = async (customerId: number) => {
    return await $api(`/api/admin/customers/${customerId}/invite-portal-user`, {
      method: "POST",
    })
  }

  const updateTenant = async (id: number, body: Record<string, any>) => {
    return await $api(`/api/admin/tenants/${id}`, {
      method: "PUT",
      body,
    })
  }

  const startTenantExport = async (id: number): Promise<TenantExportJob> => {
    return await $api(`/api/admin/tenants/${id}/exports`, {
      method: "POST",
    })
  }

  const getTenantExport = async (exportId: string): Promise<TenantExportJob> => {
    return await $api(`/api/admin/tenant-exports/${exportId}`)
  }

  const downloadTenantExport = async (exportId: string): Promise<Blob> => {
    return await $api(`/api/admin/tenant-exports/${exportId}/download`, {
      responseType: "blob",
    })
  }

  const importTenant = async (body: Record<string, any> | FormData): Promise<TenantImportResult> => {
    return await $api("/api/admin/tenant-imports", {
      method: "POST",
      body,
    })
  }

  const getSystemStatus = async (): Promise<SystemStatus> => {
    return await $api("/api/admin/system-status")
  }

  const getInstanceAgents = async (): Promise<{ agents: InstanceAgent[] }> => {
    const response = await $api("/api/instance-agents") as any
    return { agents: response?.agents || [] }
  }

  const createInstanceAgent = async (body: Record<string, any>): Promise<CreateInstanceAgentResult> => {
    return await $api("/api/instance-agents", {
      method: "POST",
      body,
    })
  }

  const updateInstanceAgent = async (id: string, body: Record<string, any>): Promise<{ agent: InstanceAgent }> => {
    return await $api(`/api/instance-agents/${id}`, {
      method: "PATCH",
      body,
    })
  }

  return {
    getOverview,
    getSystemStatus,
    getInstanceAgents,
    createInstanceAgent,
    updateInstanceAgent,
    createUser,
    createUserForProfile,
    updateUser,
    updateUserAccess,
    createTenant,
    invitePortalUser,
    updateTenant,
    startTenantExport,
    getTenantExport,
    downloadTenantExport,
    importTenant,
  }
}
