import { shoppingItemApi } from '../api/client'; import type { ShoppingItem, CreateShoppingItemRequest, UpdateShoppingItemRequest, MarkAsPurchasedRequest } from '../types'; import { handleApiError } from '../utils/errorHandler'; export const shoppingService = { async getAllByFamily(familyId: number): Promise { try { const res = await shoppingItemApi.getAllByFamily(familyId); return res.data; } catch (error) { handleApiError(error); } }, async getById(familyId: number, itemId: number): Promise { try { const res = await shoppingItemApi.getById(familyId, itemId); return res.data; } catch (error) { handleApiError(error); } }, async create(familyId: number, data: CreateShoppingItemRequest): Promise { try { const res = await shoppingItemApi.create(familyId, data); return res.data; } catch (error) { handleApiError(error); } }, async update(familyId: number, itemId: number, data: UpdateShoppingItemRequest): Promise { try { const res = await shoppingItemApi.update(familyId, itemId, data); return res.data; } catch (error) { handleApiError(error); } }, async delete(familyId: number, itemId: number): Promise { try { await shoppingItemApi.delete(familyId, itemId); } catch (error) { handleApiError(error); } }, async markAsPurchased(familyId: number, itemId: number, isPurchased: boolean): Promise { try { const data: MarkAsPurchasedRequest = { is_purchased: isPurchased }; const res = await shoppingItemApi.markAsPurchased(familyId, itemId, data); return res.data; } catch (error) { handleApiError(error); } }, async markAllAsPurchased(familyId: number): Promise { try { const res = await shoppingItemApi.markAllAsPurchased(familyId); return res.data.affected_rows; } catch (error) { handleApiError(error); } }, async clearAll(familyId: number): Promise { try { const res = await shoppingItemApi.clearAll(familyId); return res.data.affected_rows; } catch (error) { handleApiError(error); } }, sortItems(items: ShoppingItem[]): { pending: ShoppingItem[]; purchased: ShoppingItem[] } { const pending = items.filter((item) => !item.is_purchased); const purchased = items.filter((item) => item.is_purchased); return { pending, purchased }; }, getStats(items: ShoppingItem[]): { total: number; purchased: number; pending: number; progress: number } { const total = items.length; const purchased = items.filter((item) => item.is_purchased).length; const pending = total - purchased; const progress = total > 0 ? (purchased / total) * 100 : 0; return { total, purchased, pending, progress }; }, };