import axios from 'axios'

import { apiClient } from '@/shared/api/client'
import type { ApiResponse } from '@/shared/types/types'
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'
  password_must_change: boolean
  roles: AdminRole[]
  permissions: string[]
  last_login_at?: string
}

export interface AdminRefreshData {
  refreshed: boolean
  expires_in: number
}

export interface AdminLoginData {
  admin: AdminUser
}

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 { data } = await axios.post<ApiResponse<AdminRefreshData>>(
    '/api/admin/auth/refresh',
    {},
    { timeout: 10000, withCredentials: true }
  )
  return data.data
}
