import { computed, ref } from 'vue'

export type UserRole = 'admin' | 'user'
export type UserStatus = 'active' | 'disabled'

export interface AuthUser {
  id: number
  username: string
  display_name: string
  role: UserRole
  status: UserStatus
  last_login_at: string | null
  created_at: string | null
  updated_at: string | null
}

export const currentUser = ref<AuthUser | null>(null)
export const authResolved = ref(false)
export const isAdmin = computed(() => currentUser.value?.role === 'admin')

let pendingLoad: Promise<AuthUser | null> | null = null

export function defaultRouteFor(user: AuthUser): string {
  return user.role === 'admin' ? '/' : '/demand-map'
}

export async function loadCurrentUser(force = false): Promise<AuthUser | null> {
  if (authResolved.value && !force) return currentUser.value
  if (pendingLoad && !force) return pendingLoad

  pendingLoad = (async () => {
    try {
      const response = await fetch('/api/auth/me')
      if (!response.ok) {
        currentUser.value = null
        return null
      }
      const payload = await response.json() as { user: AuthUser }
      currentUser.value = payload.user
      return payload.user
    } catch {
      currentUser.value = null
      return null
    } finally {
      authResolved.value = true
      pendingLoad = null
    }
  })()
  return pendingLoad
}

export async function login(username: string, password: string): Promise<AuthUser> {
  const response = await fetch('/api/auth/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password }),
  })
  if (!response.ok) {
    const payload = await response.json().catch(() => null) as { detail?: string } | null
    throw new Error(payload?.detail || '登录失败，请稍后重试')
  }
  const payload = await response.json() as { user: AuthUser }
  currentUser.value = payload.user
  authResolved.value = true
  return payload.user
}

export async function logout(): Promise<void> {
  try {
    await fetch('/api/auth/logout', { method: 'POST' })
  } finally {
    currentUser.value = null
    authResolved.value = true
  }
}
