import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type {
  App,
  AppParam,
  ApiKey,
  ApiKeyParam,
  Developer,
  DeveloperApplyParam,
  Project,
  ProjectParam,
  ProjectMember,
  Version,
  VersionParam,
  Notification,
  NotificationParam,
  Apply,
  ApplyParam,
} from '@/types/developer'

// ==================== 项目/应用相关 ====================
// 注意：后端使用 AppProduct 作为项目/应用的概念，路径为 /app/product

/**
 * 获取我的项目列表（我创建的应用）
 */
export async function pageMyProject(params?: ProjectParam) {
  const res = await request.get<ApiResult<PageResult<Project>>>('/app/product/my/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取项目列表（分页查询应用列表）
 */
export async function pageProject(params?: ProjectParam) {
  const res = await request.get<ApiResult<PageResult<Project>>>('/app/product/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取项目详情
 */
export async function getProject(id: number) {
  const res = await request.get<ApiResult<Project>>(`/app/product/detail/${id}`)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 创建项目
 */
export async function createProject(data: Partial<Project>) {
  const res = await request.post<ApiResult<unknown>>('/app/product/create', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 更新项目
 */
export async function updateProject(data: Partial<Project>) {
  const res = await request.put<ApiResult<unknown>>('/app/product/update', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 删除项目
 */
export async function deleteProject(id: number) {
  const res = await request.del<ApiResult<unknown>>(`/app/product/delete/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 获取项目成员列表（使用应用用户服务）
 */
export async function listProjectMember(projectId: number) {
  const res = await request.get<ApiResult<ProjectMember[]>>(`/app/app-user/page`, { appId: projectId })
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 添加项目成员
 */
export async function addProjectMember(projectId: number, data: Partial<ProjectMember>) {
  const res = await request.post<ApiResult<unknown>>(`/app/app-user`, { ...data, appId: projectId })
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 移除项目成员
 */
export async function removeProjectMember(projectId: number, memberId: number) {
  const res = await request.del<ApiResult<unknown>>(`/app/app-user/${memberId}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

// ==================== 应用相关（别名，与项目共用）====================

/**
 * 分页查询我的应用（创建的应用）
 */
export async function pageMyApp(params?: AppParam) {
  const res = await request.get<ApiResult<PageResult<App>>>('/app/product/my/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 分页查询我参与的应用（通过邀请加入的应用）
 */
export async function pageJoinedApp(params?: AppParam) {
  const res = await request.get<ApiResult<PageResult<App>>>('/app/product/joined/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取应用列表
 */
export async function pageApp(params?: AppParam) {
  const res = await request.get<ApiResult<PageResult<App>>>('/app/product/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取应用详情
 */
export async function getApp(id: number) {
  const res = await request.get<ApiResult<App>>(`/app/product/detail/${id}`)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 创建应用
 */
export async function createApp(data: Partial<App>) {
  const res = await request.post<ApiResult<unknown>>('/app/product/create', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 更新应用
 */
export async function updateApp(data: Partial<App>) {
  const res = await request.put<ApiResult<unknown>>('/app/product/update', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 删除应用
 */
export async function deleteApp(id: number) {
  const res = await request.del<ApiResult<unknown>>(`/app/product/delete/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

// ==================== API Key 相关 ====================
// 对应后端 AppCredentialController，路径为 /app/app-credential

/**
 * 获取 API Key 列表
 */
export async function pageApiKey(params?: ApiKeyParam) {
  const res = await request.get<ApiResult<PageResult<ApiKey>>>('/app/app-credential/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取 API Key 列表（不分页）
 */
export async function listApiKey(params?: ApiKeyParam) {
  const res = await request.get<ApiResult<ApiKey[]>>('/app/app-credential', params)
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 创建 API Key
 */
export async function createApiKey(data: Partial<ApiKey>) {
  const res = await request.post<ApiResult<unknown>>('/app/app-credential', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 更新 API Key
 */
export async function updateApiKey(data: Partial<ApiKey>) {
  const res = await request.put<ApiResult<unknown>>('/app/app-credential', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 删除 API Key
 */
export async function deleteApiKey(id: number) {
  const res = await request.del<ApiResult<unknown>>(`/app/app-credential/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 重置 API Key Secret
 */
export async function resetApiKeySecret(id: number) {
  const res = await request.post<ApiResult<unknown>>(`/app/app-credential/resetSecret/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

// ==================== 版本发布相关 ====================
// 对应后端 AppVersionController，路径为 /app/app-version

/**
 * 获取版本列表
 */
export async function pageVersion(params?: VersionParam) {
  const res = await request.get<ApiResult<PageResult<Version>>>('/app/app-version/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取版本详情
 */
export async function getVersion(id: number) {
  const res = await request.get<ApiResult<Version>>(`/app/app-version/${id}`)
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 创建版本
 */
export async function createVersion(data: Partial<Version>) {
  const res = await request.post<ApiResult<unknown>>('/app/app-version', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 发布版本
 */
export async function publishVersion(id: number) {
  const res = await request.post<ApiResult<unknown>>(`/app/app-version/publish/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 回滚版本
 */
export async function rollbackVersion(id: number) {
  const res = await request.post<ApiResult<unknown>>(`/app/app-version/rollback/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

// ==================== 开发者相关 ====================
// 对应后端 GitAccountController，路径为 /app/developer

/**
 * 获取开发者信息（Git账号绑定状态）
 */
export async function getDeveloperInfo() {
  const res = await request.get<ApiResult<Developer>>('/app/developer/git-account')
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 申请成为开发者（绑定Git账号）
 */
export async function applyDeveloper(data: DeveloperApplyParam) {
  const res = await request.post<ApiResult<unknown>>('/app/developer/git-account', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 更新开发者信息（更新Git账号）
 */
export async function updateDeveloperInfo(data: Partial<Developer>) {
  const res = await request.put<ApiResult<unknown>>('/app/developer/git-account', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 获取Gitea服务器信息
 */
export async function getGiteaInfo() {
  const res = await request.get<ApiResult<{ url: string; version: string; registrationEnabled: boolean }>>('/app/developer/gitea-info')
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

// ==================== 消息通知相关 ====================
// 对应后端 AppNotificationController，路径为 /app/notification

/**
 * 获取通知列表
 */
export async function pageNotification(params?: NotificationParam) {
  const res = await request.get<ApiResult<PageResult<Notification>>>('/app/notification/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取最近通知（铃铛下拉）
 */
export async function getRecentNotifications(type?: string, limit?: number) {
  const res = await request.get<ApiResult<Notification[]>>('/app/notification/recent', { type, limit })
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取未读通知数量
 */
export async function getUnreadCount() {
  const res = await request.get<ApiResult<{ count: number }>>('/app/notification/unread-count')
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 标记通知为已读
 */
export async function markAsRead(id: number) {
  const res = await request.put<ApiResult<unknown>>(`/app/notification/read/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 标记所有通知为已读
 */
export async function markAllAsRead(type?: string) {
  const res = await request.put<ApiResult<unknown>>('/app/notification/read-all', { type })
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 删除通知
 */
export async function deleteNotification(id: number) {
  const res = await request.del<ApiResult<unknown>>(`/app/notification/${id}`)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 清空已读通知
 */
export async function clearReadNotifications(type?: string) {
  const res = await request.del<ApiResult<unknown>>('/app/notification/clear-read', { type })
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

// ==================== 权限审批相关 ====================
// 对应后端 AppPermissionRequestController，路径为 /app/developer/permission-requests

/**
 * 获取申请列表
 */
export async function pageApply(params?: ApplyParam) {
  const res = await request.get<ApiResult<PageResult<Apply>>>('/app/developer/permission-requests/page', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取我的申请列表
 */
export async function pageMyApply(params?: ApplyParam) {
  const res = await request.get<ApiResult<PageResult<Apply>>>('/app/developer/permission-requests', params)
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取权限申请统计
 */
export async function getApplyStats() {
  const res = await request.get<ApiResult<{ [key: string]: number }>>('/app/developer/permission-requests/stats')
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 获取可申请的仓库列表
 */
export async function getAvailableRepos() {
  const res = await request.get<ApiResult<Array<{ name: string; fullName: string }>>>('/app/developer/permission-requests/available-repos')
  if (res.code === 0) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 创建申请
 */
export async function createApply(data: { repo: string; reason: string; gitUsername?: string }) {
  const res = await request.post<ApiResult<unknown>>('/app/developer/permission-requests', data)
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 审批申请-通过
 */
export async function approveApply(id: number, note?: string) {
  const res = await request.put<ApiResult<unknown>>(`/app/developer/permission-requests/${id}/approve`, { note })
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}

/**
 * 审批申请-拒绝
 */
export async function rejectApply(id: number, reason: string) {
  const res = await request.put<ApiResult<unknown>>(`/app/developer/permission-requests/${id}/reject`, { reason })
  if (res.code === 0) return res.message
  return Promise.reject(new Error(res.message))
}
