import request from './request'
import type {
  AutoGroupPreviewGroup,
  FamilyPriceOverrideRow,
  PaginatedResult,
  ProductFamily,
} from '@/types'

export const productFamiliesApi = {
  list: (params: { keyword?: string; page?: number; pageSize?: number }) => {
    return request.get<any, PaginatedResult<ProductFamily>>('/product-families', { params })
  },

  detail: (id: string) => {
    return request.get<any, ProductFamily>(`/product-families/${id}`)
  },

  create: (data: {
    familyName: string
    familyCode?: string
    familyImage?: string
    originGoodIds?: string[]
    primaryOriginGoodId?: string
  }) => {
    return request.post<any, ProductFamily>('/product-families', data)
  },

  patch: (id: string, data: Record<string, unknown>) => {
    return request.patch<any, ProductFamily>(`/product-families/${id}`, data)
  },

  autoGroup: (apply: boolean) => {
    return request.post<any, { applied: number; groups: AutoGroupPreviewGroup[] }>(
      '/product-families/auto-group',
      { apply },
    )
  },

  updateMembers: (id: string, data: { addOriginGoodIds?: string[]; removeOriginGoodIds?: string[] }) => {
    return request.post<any, ProductFamily>(`/product-families/${id}/members`, data)
  },

  createCustomMember: (id: string, data: Record<string, unknown>) => {
    return request.post<any, unknown>(`/product-families/${id}/members/custom`, data)
  },

  recompute: (id: string) => {
    return request.post<any, ProductFamily>(`/product-families/${id}/recompute`)
  },

  listOverrides: (id: string) => {
    return request.get<any, { items: FamilyPriceOverrideRow[] }>(`/product-families/${id}/price-overrides`)
  },

  putOverrides: (id: string, items: Array<Record<string, unknown>>) => {
    return request.put<any, { items: FamilyPriceOverrideRow[] }>(`/product-families/${id}/price-overrides`, { items })
  },

  deleteOverrides: (id: string, cells: Array<Record<string, unknown>>) => {
    return request.delete<any, { items: FamilyPriceOverrideRow[] }>(`/product-families/${id}/price-overrides`, {
      data: { cells },
    })
  },
}
