// 应用产品（对齐 PC /developer/apps 与 /admin 应用管理，基址走 websopy-api）
import { get, post, put, del } from '@/utils/request'
import { WebsopyBaseUrl } from '@/config/app'

const BASE = '/app/product'

export interface AppProduct {
  productId?: number
  productName?: string
  productCode?: string
  appType?: number
  description?: string
  logo?: string
  publishStatus?: string
  status?: number
  adminUrl?: string
  homeUrl?: string
  createTime?: string
  userId?: number
  tenantId?: number
  rejectReason?: string
  [key: string]: any
}

/** 我的应用（创建者） */
export async function getMyApps(params: any) {
  const res = await get<any>(`${BASE}/my/page`, params, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

/** 开发者应用列表 */
export async function getDeveloperApps(params?: any) {
  const res = await get<any>(`${BASE}/list`, params, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

/** 创建应用 */
export async function addAppProduct(data: any) {
  const res = await post<any>(`${BASE}/create`, data, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '创建失败'))
}

/** 发布审核列表（管理端，publishStatus=pending_review） */
export async function pagePublishReviews(params: any) {
  const res = await get<any>(`${BASE}/page`, { ...params, publishStatus: 'pending_review' }, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

/** 全部应用（管理端） */
export async function pageAllApps(params: any) {
  const res = await get<any>(`${BASE}/page`, params, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

/** 更新应用 */
export async function updateAppProduct(data: any) {
  const res = await put<any>(`${BASE}/update`, data, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '更新失败'))
}

/** 删除应用 */
export async function deleteAppProduct(id: number) {
  const res = await del<any>(`${BASE}/delete/${id}`, {}, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '删除失败'))
}

/** 审核通过 */
export async function approvePublishReview(id: number) {
  const res = await post<any>(`${BASE}/approve/${id}`, {}, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.message
  return Promise.reject(new Error(res?.message || '操作失败'))
}

/** 审核拒绝 */
export async function rejectPublishReview(params: { productId: number; rejectReason: string }) {
  const res = await post<any>(
    `${BASE}/reject/${params.productId}?reason=${encodeURIComponent(params.rejectReason)}`,
    {},
    { baseUrl: WebsopyBaseUrl }
  )
  if (res?.code === 0) return res.message
  return Promise.reject(new Error(res?.message || '操作失败'))
}
