export interface LoginResponse {
  message: string
  user: UserInfo
}

export interface UserInfo {
  id: string
  name: 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')
}

// 检查cookie是否过期（通过检查session cookie是否存在）
export function isCookieExpired(): boolean {
  const sessionCookie = getSessionCookie()
  return !sessionCookie
}

export const loginApi = async (username: string, password: string): Promise<LoginResponse> => {
  const formData = new URLSearchParams()
  formData.append('cmd', 'login')
  formData.append('usr', username)
  formData.append('pwd', password)

  const response = await fetch('/api/action/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    },
    credentials: 'include',
    body: formData
  })

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}))
    throw new Error(errorData.message || errorData.exc || '登录请求失败')
  }

  const data = await response.json()
  
  // 获取用户信息
  const userInfo = await getUserInfoApi()
  
  return { message: data.message || 'Logged In', user: userInfo }
}

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

  if (!response.ok) {
    if (response.status === 401 || response.status === 403) {
      const error = new Error('Cookie已过期，请重新登录')
      // @ts-ignore
      error.status = response.status
      throw error
    }
    const errorData = await response.json().catch(() => ({}))
    throw new Error(errorData.message || errorData.exc || '获取用户信息失败')
  }

  const data = await response.json()
  const userInfo = data.message || data
  
  return {
    id: userInfo.user || userInfo.name || userInfo.username || '',
    name: userInfo.user || userInfo.name || '',
    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',
    // Permission fields from backend
    recent: userInfo.recent || '[]',
    can_read: userInfo.can_read || [],
    can_create: userInfo.can_create || [],
    can_search: userInfo.can_search || []
  }
}

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

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}))
    throw new Error(errorData.message || errorData.exc || '登出失败')
  }
}

// 注册接口
export interface SignupRequest {
  username: string
  password: string
  email?: string
  phone_number?: string
}

export interface SignupResponse {
  success: boolean
  message?: string
  error?: string
  user?: UserInfo
}

export const signupApi = async (data: SignupRequest): Promise<SignupResponse> => {
  try {
    const response = await fetch('/api/action/jingrow.core.pagetype.user.user.sign_up', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        email: data.email,
        full_name: data.username,
        redirect_to: '/'
      })
    })

    const result = await response.json().catch(() => ({}))
    
    if (!response.ok) {
      const errorMsg = result.message || result.exc || `注册请求失败 (HTTP ${response.status})`
      return { success: false, error: errorMsg }
    }
    
    if (result.message === 'success') {
      return { 
        success: true, 
        message: '注册成功，请检查邮箱验证'
      }
    }
    
    return { 
      success: false, 
      error: result.message || '注册失败' 
    }
  } catch (error: any) {
    return { 
      success: false, 
      error: error.message || '网络错误，请检查网络连接后重试' 
    }
  }
}
