import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http' import type { SaveSupplierRequest, Supplier, SupplierPage, SupplierQuery, SupplierStats, SupplierStatus } from '@/modules/suppliers/types' const basePath = '/platform/v1/suppliers' const platformScope = 0 const id = (value: string | number | null | undefined) => value == null ? null : String(value) function normalizeSupplier(raw: Supplier): Supplier { return { ...raw, id: String(raw.id), tenantId: String(raw.tenantId), carrierCodes: [...raw.carrierCodes], licenseFileId: id(raw.licenseFileId), createdBy: id(raw.createdBy), updatedBy: id(raw.updatedBy), version: Number(raw.version), deleted: Boolean(raw.deleted), } } export async function listSuppliers(query: SupplierQuery): Promise { const response = await http.get, ApiEnvelope>(basePath, { params: { page: query.page ?? 1, size: query.size ?? 20, category: query.category, region: query.region?.trim() || undefined, status: query.status || undefined, keyword: query.keyword?.trim() || undefined, carrierCode: query.carrierCode || undefined, }, }) const data = unwrapApiResponse(response) return { records: data.records.map(normalizeSupplier), page: Number(data.page), size: Number(data.size), total: Number(data.total), pages: Number(data.pages) } } export async function getSupplierStats(): Promise { const response = await http.get, ApiEnvelope>(`${basePath}/stats`) const data = unwrapApiResponse(response) return { booking: Number(data.booking), customs: Number(data.customs), trucking: Number(data.trucking), certificate: Number(data.certificate) } } export async function getSupplier(supplierId: string): Promise { const response = await http.get, ApiEnvelope>(`${basePath}/${encodeURIComponent(supplierId)}`, { params: { tenantId: platformScope } }) return normalizeSupplier(unwrapApiResponse(response)) } export async function createSupplier(payload: SaveSupplierRequest): Promise { const response = await http.post, ApiEnvelope>(basePath, payload, { params: { tenantId: platformScope } }) return String(unwrapApiResponse(response)) } export async function updateSupplier(supplierId: string, payload: SaveSupplierRequest): Promise { const response = await http.put, ApiEnvelope>(`${basePath}/${encodeURIComponent(supplierId)}`, payload, { params: { tenantId: platformScope } }) return unwrapApiResponse(response) } export async function changeSupplierStatus(supplierId: string, status: SupplierStatus): Promise { const response = await http.patch, ApiEnvelope>(`${basePath}/${encodeURIComponent(supplierId)}/status`, { status }, { params: { tenantId: platformScope } }) return unwrapApiResponse(response) }