import { create } from 'zustand'
import * as OrderController from '../client/controllers/OrderController'
import { OrderTableQuery } from '../client/request/GetOrderTableRequest'
import { OrderResponse } from '../client/response'

type OrderData = {
	orders: OrderResponse[]
}

type OrderActions = {
	sync: (page: number, filter: number, searchParams: OrderTableQuery) => Promise<OrderResponse[]>
	createOrder: (orderer: string, dateDue: string) => Promise<OrderResponse>
	getOrderById: (orderId: number) => Promise<OrderResponse>
	deleteOrder: (orderId: number) => Promise<void>
}

export const useOrderStore = create<OrderData & OrderActions>((set, get) => ({
	orders: [],
	sync: async (page: number, filter: number, searchParams: OrderTableQuery): Promise<OrderResponse[]> => {
		const resp = await OrderController.GetOrderTable(page, filter, searchParams)
		set((state) => ({
			...state,
			orders: resp
		}))
		return resp
	},
	createOrder: async (orderer: string, dateDue: string): Promise<OrderResponse> => {
		const resp = await OrderController.CreateOrder(orderer, dateDue)
		console.log(resp)
		set((state) => ({
			...state,
			orders: [...state.orders, resp]
		}))
		console.log(get().orders)
		return resp
	},
	getOrderById: async (orderId: number): Promise<OrderResponse> => {
		return await OrderController.GetOrderById(orderId)
	},
	deleteOrder: async (orderId): Promise<void> => {
		await OrderController.DeleteOrder(orderId)
	}
}))
