import { FetchState, Ticket } from "@frontend/kitui"
import { create } from "zustand"
import { devtools } from "zustand/middleware"


interface TicketStore {
    ticketCount: number;
    tickets: Ticket[];
    apiPage: number;
    ticketsPerPage: number;
    ticketsFetchState: FetchState;
}

const initialState: TicketStore = {
	ticketCount: 0,
	tickets: [],
	apiPage: 0,
	ticketsPerPage: 10,
	ticketsFetchState: "idle",
}

export const useTicketStore = create<TicketStore>()(
	devtools(
		(set, get) => initialState,
		{
			name: "Tickets"
		}
	)
)

export const setTicketCount = (ticketCount: number) => useTicketStore.setState({ ticketCount })

export const setTicketApiPage = (apiPage: number) => useTicketStore.setState({ apiPage: apiPage })

export const updateTickets = (receivedTickets: Ticket[]) => {
	const state = useTicketStore.getState()
	const ticketIdToTicketMap: { [ticketId: string]: Ticket; } = {};

	[...state.tickets, ...receivedTickets].forEach(ticket => ticketIdToTicketMap[ticket.id] = ticket)

	useTicketStore.setState({ tickets: Object.values(ticketIdToTicketMap) })
}

export const clearTickets = () => useTicketStore.setState({ ...initialState })

export const setTicketsFetchState = (ticketsFetchState: FetchState) => useTicketStore.setState({ ticketsFetchState })
