import axios from 'axios'

import { apiClient } from '@/shared/api/client'
import type { ApiResponse } from '@/shared/types/types'
import { getRefreshToken, setAuthTokens } from '@/shared/utils/authStorage'
import type { UserStatus } from '@/shared/types/status'

export interface AdminRole {
  id: number
  code: string
  name: string
}

export interface AdminUser {
  id: number
  username: string
  nickname: string
  status: UserStatus
  support_status: 'online' | 'offline' | 'busy'
  roles: AdminRole[]
  permissions: string[]
  last_login_at?: string
}

export interface AdminTokenPair {
  access_token: string
  refresh_token: string
  token_type: string
  expires_in: number
}

export interface AdminLoginData {
  admin: AdminUser
  tokens: AdminTokenPair
}

export interface AdminCaptcha {
  captcha_id: string
  image: string
  expires_in: number
}

export async function fetchAdminCaptcha() {
  const { data } = await apiClient.get<ApiResponse<AdminCaptcha>>('/admin/auth/captcha')
  return data.data
}

export async function loginAdmin(username: string, password: string, captchaId: string, captchaCode: string) {
  const { data } = await apiClient.post<ApiResponse<AdminLoginData>>('/admin/auth/login', {
    username,
    password,
    captcha_id: captchaId,
    captcha_code: captchaCode,
  })
  return data.data
}

export async function fetchAdminMe() {
  const { data } = await apiClient.get<ApiResponse<AdminUser>>('/admin/me')
  return data.data
}

export async function logoutAdmin() {
  const { data } = await apiClient.post<ApiResponse<{ logged_out: boolean }>>('/admin/auth/logout')
  return data.data
}

export async function updateSupportStatus(status: 'online' | 'offline' | 'busy') {
  const { data } = await apiClient.put<ApiResponse<{ updated: boolean; support_status: string }>>('/admin/me/support-status', {
    status,
  })
  return data.data
}

/** Manually refresh admin token (uses raw axios to avoid interceptor recursion) */
export async function refreshAdminSession() {
  const refreshToken = getRefreshToken('admin')
  if (!refreshToken) throw new Error('no refresh token')
  const { data } = await axios.post<ApiResponse<AdminTokenPair>>('/api/admin/auth/refresh', { refresh_token: refreshToken }, { timeout: 10000 })
  setAuthTokens('admin', data.data)
  return data.data
}
