// Cashier day-end close-out (docs/14 Sales API). Preview shows what closing right now
// would include (or the existing close, if already closed); close is the one-shot,
// idempotent action that locks the day's Posted slips and posts the consolidated GL entry.
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import { CreateSalesDayEndRequest, SalesDayEnd, SalesDayEndPreview, SalesDayEndSummary } from "@/types/sales"

export interface ListSalesDayEndsParams {
  page?: number
  pageSize?: number
  cashierUserId?: number
}

export const salesDayEndApi = {
  list(params: ListSalesDayEndsParams = {}): Promise<PagedResponse<SalesDayEndSummary>> {
    return apiRequest<PagedResponse<SalesDayEndSummary>>(`/sales-day-end${buildQuery(params)}`)
  },

  get(salesDayEndId: number): Promise<SalesDayEnd> {
    return apiRequest<SalesDayEnd>(`/sales-day-end/${salesDayEndId}`)
  },

  preview(cashierUserId: number, businessDate?: string): Promise<SalesDayEndPreview> {
    return apiRequest<SalesDayEndPreview>(`/sales-day-end/preview${buildQuery({ cashierUserId, businessDate })}`)
  },

  /** Idempotent — closing an already-closed date replays the existing record. */
  close(request: CreateSalesDayEndRequest): Promise<SalesDayEnd> {
    return apiRequest<SalesDayEnd>("/sales-day-end", { method: "POST", body: request })
  },
}
