import { download, get } from '@/lib/http/client'
import type { LoginLogListParams, LoginLogListResponse } from '@/types/login-log'

interface BackendListResponse<T> {
  list: T[]
  total: number
  page: number
  size: number
}

export async function listLoginLogs(params?: LoginLogListParams): Promise<LoginLogListResponse> {
  const result = await get<BackendListResponse<LoginLogListResponse['items'][number]>>(
    '/logs/login',
    params as Record<string, string | number | boolean | undefined>,
  )

  return {
    items: result.list,
    total: result.total,
    page: result.page,
    page_size: result.size,
  }
}

export async function listMyLoginLogs(params?: Pick<LoginLogListParams, 'page' | 'page_size'>): Promise<LoginLogListResponse> {
  const result = await get<BackendListResponse<LoginLogListResponse['items'][number]>>(
    '/logs/login/me',
    params as Record<string, string | number | boolean | undefined>,
  )

  return {
    items: result.list,
    total: result.total,
    page: result.page,
    page_size: result.size,
  }
}

function triggerFileDownload(blob: Blob, filename: string) {
  const link = document.createElement('a')
  const objectUrl = window.URL.createObjectURL(blob)
  link.href = objectUrl
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(objectUrl)
}

export interface ExportLoginLogsParams {
  user_id?: number
  status?: number
  format?: 'csv' | 'xlsx'
  start_at?: string
  end_at?: string
}

export async function exportLoginLogs(params?: ExportLoginLogsParams): Promise<void> {
  const format = params?.format || 'csv'
  const blob = await download('/logs/login/export', {
    user_id: params?.user_id,
    status: params?.status,
    format,
    start_at: params?.start_at,
    end_at: params?.end_at,
  })

  triggerFileDownload(blob, `login_logs_${new Date().toISOString().slice(0, 10)}.${format}`)
}
