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')
}

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

export const loginApi = async (username: string, password: string): Promise<LoginResponse> => {
  const response = await fetch(`/jingrow/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    credentials: 'include',
    body: JSON.stringify({
      username: username,
      password: password
    })
  })

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

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

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

  if (!response.ok) {
    // 401或403表示cookie过期或未授权
    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.detail || errorData.message || '获取用户信息失败')
  }

  const data = await response.json()
  
  if (data.success && data.user_info) {
    return data.user_info
  } else {
    throw new Error(data.message || data.detail || '获取用户信息失败')
  }
}

// 登出
export const logoutApi = async (): Promise<void> => {
  const response = await fetch(`/jingrow/logout`, {
    method: 'POST',
    headers: { 
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    credentials: 'include'
  })

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

// 注册接口
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(`/jingrow/signup`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify(data)
    })

    // 先克隆响应，以便可以多次读取（如果需要）
    const responseClone = response.clone()
    
    let result: any = {}
    
    // 尝试解析响应体
    try {
      result = await response.json()
    } catch (e) {
      // 如果JSON解析失败，尝试读取文本
      try {
        const text = await responseClone.text()
        return { 
          success: false, 
          error: text || `注册请求失败 (HTTP ${response.status})` 
        }
      } catch (textError) {
        return { 
          success: false, 
          error: `注册请求失败 (HTTP ${response.status})` 
        }
      }
    }
    
    // 如果响应不成功，提取错误消息
    if (!response.ok) {
      // FastAPI HTTPException 返回格式: {"detail": "错误消息"}
      const errorMsg = result.detail || `注册请求失败 (HTTP ${response.status})`
      return { success: false, error: errorMsg }
    }
    
    // 检查业务逻辑错误（success 为 false）
    if (result.success === false) {
      const errorMsg = result.error || result.message || '注册失败'
      return { success: false, error: errorMsg }
    }
    
    return { 
      success: true, 
      message: result.message || '注册成功',
      user: result.user || undefined
    }
  } catch (error: any) {
    // 处理网络错误或其他异常
    return { 
      success: false, 
      error: error.message || '网络错误，请检查网络连接后重试' 
    }
  }
}
