import type {
  ProductFormValues,
  ProductItem,
  ProductListParams,
  ProductListResponse,
  ProductStatusUpdatePayload,
} from '@/pages/ProductList/data';
import { request } from '@umijs/max';

type LegacyInventoryStatus = 'in_stock' | 'out_of_stock';

type LegacyProductItem = ProductItem & {
  price: number;
  inventoryStatus: LegacyInventoryStatus;
};

type LegacyProductListResponse = Omit<ProductListResponse, 'data'> & {
  data: LegacyProductItem[];
};

/** 获取商品列表 GET /api/products */
export async function getProductList(params?: ProductListParams) {
  return request<ProductListResponse>('/api/products', {
    method: 'GET',
    params,
  });
}

/** 获取商品详情 GET /api/products/:id */
export async function getProductDetail(id: string) {
  return request<ProductItem>(`/api/products/${id}`, {
    method: 'GET',
  });
}

/** 新增商品 POST /api/products */
export async function createProduct(data: ProductFormValues) {
  return request<ProductItem>('/api/products', {
    method: 'POST',
    data,
  });
}

/** 编辑商品 PUT /api/products/:id */
export async function updateProduct(data: ProductFormValues) {
  if (!data.id) {
    throw new Error('Product id is required');
  }
  return request<ProductItem>(`/api/products/${data.id}`, {
    method: 'PUT',
    data,
  });
}

/** 批量更新状态 PUT /api/products/status */
export async function updateProductStatus(data: ProductStatusUpdatePayload) {
  return request<{ success: boolean }>('/api/products/status', {
    method: 'PUT',
    data,
  });
}

/** 删除商品 DELETE /api/products/:id */
export async function deleteProduct(id: string) {
  return request<{ success: boolean }>(`/api/products/${id}`, {
    method: 'DELETE',
  });
}

/** 兼容旧调用 */
export async function queryProductList(
  params?: Record<string, unknown>,
): Promise<LegacyProductListResponse> {
  const response = await getProductList(params as ProductListParams);
  const normalized = Array.isArray(response)
    ? { data: response, total: response.length, success: true }
    : response;

  return {
    ...normalized,
    data: normalized.data.map((item) => ({
      ...item,
      price: item.salePrice,
      inventoryStatus: item.stock === 0 ? 'out_of_stock' : 'in_stock',
    })),
  };
}
export const addProduct = createProduct;
export const removeProduct = deleteProduct;

export async function queryAttributeList(params?: Record<string, unknown>) {
  return request('/api/product/attributes', {
    method: 'GET',
    params,
  });
}

export async function saveAttribute(params: Record<string, unknown>) {
  return request('/api/product/attribute', {
    method: 'POST',
    data: params,
  });
}

export async function removeAttribute(id: string) {
  return request(`/api/product/attribute/${id}`, {
    method: 'DELETE',
  });
}
