import { request } from '@/utils/request'
import type { PageParams, PageResult } from '@/types/api'

// ============================================================
// 商品管理
//
// 后端契约：com.snack.server.module.product.controller.ProductAdminController
//   GET    /api/admin/product/page                       → Page<ProductListVO>
//   GET    /api/admin/product/{id}                       → ProductDetailVO
//   POST   /api/admin/product                            → Long
//   PUT    /api/admin/product                            → Void
//   DELETE /api/admin/product/{id}                       → Void
//   PUT    /api/admin/product/{id}/status/{status}       → Void
//   PUT    /api/admin/product/{id}/hot/{isHot}           → Void
//   PUT    /api/admin/product/{id}/new/{isNew}           → Void
//   PUT    /api/admin/product/stock/adjust               → Void  body: StockAdjustReq
// ============================================================

export interface ProductSkuItem {
  id: number
  productId: number
  skuName: string
  image: string
  price: number
  stock: number
  sales: number
  weight: number
  sort: number
}

export interface ProductItem {
  id: number
  name: string
  categoryId: number
  categoryName: string
  brand: string
  mainImage: string
  minPrice: number
  maxPrice: number
  totalStock: number
  sales: number
  status: 0 | 1
  isHot: 0 | 1
  isNew: 0 | 1
  createTime: string
}

export interface ProductDetail extends ProductItem {
  subImages: string[]
  detail: string
  originPrice: number
  viewCount: number
  skuList: ProductSkuItem[]
}

export interface ProductSkuPayload {
  id?: number
  skuName: string
  image?: string
  price: number
  stock: number
  weight?: number
  sort?: number
}

export interface ProductSavePayload {
  id?: number
  name: string
  categoryId: number
  brand?: string
  mainImage?: string
  /** 副图 JSON 数组字符串（后端约定） */
  subImages?: string
  detail?: string
  originPrice?: number
  isHot?: 0 | 1
  isNew?: 0 | 1
  status?: 0 | 1
  skuList: ProductSkuPayload[]
}

export interface ProductPageQuery extends PageParams {
  keyword?: string
  categoryId?: number
  status?: 0 | 1
  isHot?: 0 | 1
  isNew?: 0 | 1
  orderBy?: 'sales_desc' | 'price_asc' | 'price_desc' | 'create_desc'
}

export interface StockAdjustPayload {
  skuId: number
  /** 增量调整（正加负减） */
  delta?: number
  /** 目标库存（与 delta 二选一，优先 delta） */
  targetStock?: number
}

export function getProductPageApi(params: ProductPageQuery) {
  return request<PageResult<ProductItem>>({
    url: '/api/admin/product/page',
    method: 'GET',
    params
  })
}

export function getProductDetailApi(id: number) {
  return request<ProductDetail>({
    url: `/api/admin/product/${id}`,
    method: 'GET'
  })
}

export function createProductApi(payload: ProductSavePayload) {
  return request<number>({
    url: '/api/admin/product',
    method: 'POST',
    data: payload
  })
}

export function updateProductApi(payload: ProductSavePayload) {
  return request<void>({
    url: '/api/admin/product',
    method: 'PUT',
    data: payload
  })
}

export function deleteProductApi(id: number) {
  return request<void>({
    url: `/api/admin/product/${id}`,
    method: 'DELETE'
  })
}

export function updateProductStatusApi(id: number, status: 0 | 1) {
  return request<void>({
    url: `/api/admin/product/${id}/status/${status}`,
    method: 'PUT'
  })
}

export function updateProductHotApi(id: number, isHot: 0 | 1) {
  return request<void>({
    url: `/api/admin/product/${id}/hot/${isHot}`,
    method: 'PUT'
  })
}

export function updateProductNewApi(id: number, isNew: 0 | 1) {
  return request<void>({
    url: `/api/admin/product/${id}/new/${isNew}`,
    method: 'PUT'
  })
}

export function adjustStockApi(payload: StockAdjustPayload) {
  return request<void>({
    url: '/api/admin/product/stock/adjust',
    method: 'PUT',
    data: payload
  })
}

// ============================================================
// 商品分类（管理端）
//
// 后端契约（com.snack.server.module.category.controller.CategoryAdminController）：
//   GET    /api/admin/category/tree?status=        → Result<List<CategoryTreeVO>>
//   GET    /api/admin/category/children?parentId=  → Result<List<Category>>
//   GET    /api/admin/category/options            → Result<List<CategoryOptionVO>>
//   GET    /api/admin/category/{id}               → Result<Category>
//   POST   /api/admin/category                    → Result<Long>   body: CategorySaveReq
//   PUT    /api/admin/category                    → Result<Void>   body: CategorySaveReq
//   DELETE /api/admin/category/{id}               → Result<Void>
//   PUT    /api/admin/category/{id}/status/{status}  → Result<Void>
//   PUT    /api/admin/category/{id}/sort/{sort}      → Result<Void>
// ============================================================

/** 树节点（与后端 CategoryTreeVO 字段一一对应） */
export interface CategoryTreeNode {
  id: number
  name: string
  parentId: number
  level: 1 | 2 | 3
  sort: number
  icon: string
  status: 0 | 1
  createTime: string
  children?: CategoryTreeNode[]
}

/** 下拉选项（用于选择父分类） */
export interface CategoryOption {
  id: number
  name: string
  level: number
  parentId: number
}

/** 详情 / 提交请求共用 */
export interface CategorySavePayload {
  id?: number
  name: string
  parentId: number
  level: 1 | 2 | 3
  sort: number
  icon?: string
  status: 0 | 1
}

/** 兼容旧名（views/product/category.vue 之前用过的） */
export type CategoryItem = CategoryTreeNode

/** 获取分类树（status 不传 = 全部） */
export function getCategoryTreeApi(status?: 0 | 1) {
  return request<CategoryTreeNode[]>({
    url: '/api/admin/category/tree',
    method: 'GET',
    params: status === undefined ? {} : { status }
  })
}

/** 获取启用状态的下拉选项（用于选父分类） */
export function getCategoryOptionsApi() {
  return request<CategoryOption[]>({
    url: '/api/admin/category/options',
    method: 'GET'
  })
}

/** 获取分类详情 */
export function getCategoryDetailApi(id: number) {
  return request<CategorySavePayload>({
    url: `/api/admin/category/${id}`,
    method: 'GET'
  })
}

/** 创建分类 */
export function createCategoryApi(payload: CategorySavePayload) {
  return request<number>({
    url: '/api/admin/category',
    method: 'POST',
    data: payload
  })
}

/** 更新分类 */
export function updateCategoryApi(payload: CategorySavePayload) {
  return request<void>({
    url: '/api/admin/category',
    method: 'PUT',
    data: payload
  })
}

/** 删除分类 */
export function deleteCategoryApi(id: number) {
  return request<void>({
    url: `/api/admin/category/${id}`,
    method: 'DELETE'
  })
}

/** 启用 / 禁用 */
export function updateCategoryStatusApi(id: number, status: 0 | 1) {
  return request<void>({
    url: `/api/admin/category/${id}/status/${status}`,
    method: 'PUT'
  })
}

/** 调整排序 */
export function updateCategorySortApi(id: number, sort: number) {
  return request<void>({
    url: `/api/admin/category/${id}/sort/${sort}`,
    method: 'PUT'
  })
}
