import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type { AppUser, AppUserParam, CheckAccessResult } from './model'
import { APP_API_URL } from '@/config/setting'

const BASE = APP_API_URL + '/app-user'

type InviteApiItem = AppUser & {
  appName?: string
  app_name?: string
  product_name?: string
  appIcon?: string
  inviterName?: string
  inviter_name?: string
  productCode?: string
  product_code?: string
}

function normalizeInvite(invite: InviteApiItem): AppUser {
  return {
    ...invite,
    productName: invite.productName || invite.appName || invite.product_name || invite.app_name,
    productCode: invite.productCode || invite.product_code,
    icon: invite.icon || invite.appIcon || invite.avatar,
    username: invite.username || invite.inviterName || invite.inviter_name || invite.nickname
  }
}

/** 分页查询成员 */
export async function pageAppUser(params: AppUserParam) {
  const res = await request.get<ApiResult<PageResult<AppUser>>>(BASE + '/page', { params })
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 查询全部成员 */
export async function listAppUser(params?: AppUserParam) {
  const res = await request.get<ApiResult<AppUser[]>>(BASE, { params })
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 邀请成员（userId 或 phone 二选一） */
export async function inviteAppUser(data: { productId: number; userId?: number; phone?: string; role?: string }) {
  const res = await request.post<ApiResult<AppUser>>(BASE + '/invite', data)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 修改成员角色 */
export async function updateAppUserRole(id: number, role: string) {
  const res = await request.put<ApiResult<unknown>>(BASE + `/role/${id}/${role}`)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 删除成员 */
export async function removeAppUser(id: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + id)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

// ============ 邀请确认相关 ============

/** 查询当前用户的待确认邀请列表 */
export async function listPendingInvites() {
  const res = await request.get<ApiResult<InviteApiItem[]>>(BASE + '/invites/pending')
  const { code, data, message } = res.data
  if (code === 0 || code === 200) {
    return Array.isArray(data) ? data.map(normalizeInvite) : []
  }
  return Promise.reject(new Error(message))
}

/** 统计当前用户的待确认邀请数量 */
export async function countPendingInvites() {
  const res = await request.get<ApiResult<{ count: number }>>(BASE + '/invites/pending/count')
  const { code, data, message } = res.data
  if ((code === 0 || code === 200) && data) return data.count
  return Promise.reject(new Error(message))
}

/** 接受邀请 */
export async function acceptInvite(inviteId: number) {
  const res = await request.post<ApiResult<unknown>>(BASE + `/invites/${inviteId}/accept`)
  if (res.data.code === 0 || res.data.code === 200) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 拒绝邀请 */
export async function rejectInvite(inviteId: number) {
  const res = await request.post<ApiResult<unknown>>(BASE + `/invites/${inviteId}/reject`)
  if (res.data.code === 0 || res.data.code === 200) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

// ============ 权限相关 ============

/**
 * 检查当前用户是否有开发者中心访问权限
 * 返回：accessible（是否有权限）、isPlatformDeveloper（是否平台级开发者）、apps（可访问应用列表）
 */
export async function checkAppAccess() {
  const res = await request.get<ApiResult<CheckAccessResult>>(BASE + '/check-access')
  if (res.data.code === 0 && res.data.data) return res.data.data
  // 兼容 code=200
  if (res.data.code === 200 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}
