// One typed client method per Sales Return endpoint. Auto-posts an inbound
// FIFO movement on create, mirroring lib/api/purchase-returns.ts with the
// direction reversed.
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import { CreateSalesReturnRequest, SalesInvoiceLineRemaining, SalesReturn, SalesReturnSummary } from "@/types/sales"

export interface ListSalesReturnsParams {
  page?: number
  pageSize?: number
  q?: string
  customerId?: number
  warehouseId?: number
  sort?: string
}

export const salesReturnsApi = {
  list(params: ListSalesReturnsParams = {}): Promise<PagedResponse<SalesReturnSummary>> {
    return apiRequest<PagedResponse<SalesReturnSummary>>(`/sales-returns${buildQuery(params)}`)
  },

  get(returnId: number): Promise<SalesReturn> {
    return apiRequest<SalesReturn>(`/sales-returns/${returnId}`)
  },

  /** Remaining returnable qty per line of one sales invoice (invoiced qty minus already-returned). */
  getRemaining(salesInvoiceId: number): Promise<SalesInvoiceLineRemaining[]> {
    return apiRequest<SalesInvoiceLineRemaining[]>(`/sales-returns/remaining${buildQuery({ salesInvoiceId })}`)
  },

  /**
   * 400 REASON_CODE_REQUIRED without a reason; 422 if it is not a Return-context reason;
   * 409 STOCK_NEGATIVE_BLOCKED-equivalent errors do not apply here (inbound movement).
   */
  create(request: CreateSalesReturnRequest): Promise<SalesReturn> {
    return apiRequest<SalesReturn>("/sales-returns", { method: "POST", body: request })
  },
}
