const jingrowServerUrl = import.meta.env.VITE_JINGROW_SERVER_URL || ''

export interface LoginResponse {
  message: string
  user: UserInfo
}

export interface UserInfo {
  id: string
  username: string
  email: string
  avatar: string
  first_name: string
  last_name: string
  user_type: string
}

export function getSessionUser(): string | null {
  const cookies = new URLSearchParams(document.cookie.split('; ').join('&'))
  const sessionUser = cookies.get('user_id')
  if (!sessionUser || sessionUser === 'Guest') {
    return null
  }
  return sessionUser
}

export function getSessionCookie(): string | null {
  const cookies = new URLSearchParams(document.cookie.split('; ').join('&'))
  return cookies.get('sid')
}

export const loginApi = async (username: string, password: string): Promise<LoginResponse> => {
  const response = await fetch(`${jingrowServerUrl}/api/action/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    },
    credentials: 'include',
    body: new URLSearchParams({
      cmd: 'login',
      usr: username,
      pwd: password
    })
  })

  if (!response.ok) {
    throw new Error('登录请求失败')
  }

  const data = await response.json()
  
  if (data.message === 'Logged In') {
    const userInfo = await getUserInfoApi()
    return { message: data.message, user: userInfo }
  } else {
    throw new Error(data.message || '登录失败')
  }
}

// 获取用户信息
export const getUserInfoApi = async (): Promise<UserInfo> => {
  const response = await fetch(`${jingrowServerUrl}/api/action/jingrow.realtime.get_user_info`, {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    credentials: 'include'
  })

  if (!response.ok) {
    throw new Error('获取用户信息失败')
  }

  const data = await response.json()
  const userInfo = data.message || data
  
  return {
    id: userInfo.user || userInfo.name || userInfo.username,
    username: userInfo.user || userInfo.name || userInfo.username,
    email: userInfo.email || '',
    avatar: userInfo.user_image || '',
    first_name: userInfo.first_name || '',
    last_name: userInfo.last_name || '',
    user_type: userInfo.user_type || 'System User'
  }
}

// 登出
export const logoutApi = async (): Promise<void> => {
  await fetch(`${jingrowServerUrl}/api/action/logout`, {
    method: 'GET',
    headers: { 'Accept': 'application/json' },
    credentials: 'include'
  })
}

// 仅使用会话Cookie的最小鉴权头部（不影响现有API Key逻辑）
export function get_session_api_headers() {
  return {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
}
