// One typed client method per Requisition endpoint (docs/11-BACKEND-PHASE1.md §3.1, FR-PROC-01).
// In-memory sample data (lib/api/mock-data.ts) — no backend API calls.
import { PagedResponse } from "@/types/common"
import { CreateRequisitionRequest, Requisition, RequisitionStatus, RequisitionSummary } from "@/types/procurement"
import { allocateReqLineId, allocateRequisitionId, mockDelay, mockRequisitions } from "@/lib/api/mock-data"

export interface ListRequisitionsParams {
  page?: number
  pageSize?: number
  status?: RequisitionStatus
}

function toSummary(r: Requisition): RequisitionSummary {
  return {
    requisitionId: r.requisitionId,
    docNo: r.docNo,
    status: r.status,
    requestedBy: r.requestedBy,
    createdAt: r.createdAt,
    lineCount: r.lines.length,
  }
}

export const requisitionsApi = {
  list(params: ListRequisitionsParams = {}): Promise<PagedResponse<RequisitionSummary>> {
    const filtered = mockRequisitions
      .filter((r) => !params.status || r.status === params.status)
      .map(toSummary)
      .sort((a, b) => b.requisitionId - a.requisitionId)

    const page = params.page ?? 1
    const pageSize = params.pageSize ?? 20
    const start = (page - 1) * pageSize
    const items = filtered.slice(start, start + pageSize)

    return mockDelay({
      items,
      pagination: { page, pageSize, totalItems: filtered.length, totalPages: Math.ceil(filtered.length / pageSize) || 0 },
    })
  },

  get(requisitionId: number): Promise<Requisition> {
    const r = mockRequisitions.find((x) => x.requisitionId === requisitionId)
    if (!r) return Promise.reject(new Error(`Mock requisition ${requisitionId} not found`))
    return mockDelay(r)
  },

  create(request: CreateRequisitionRequest): Promise<Requisition> {
    if (request.lines.length === 0) {
      return Promise.reject(new Error("A requisition needs at least one line."))
    }
    const requisition: Requisition = {
      requisitionId: allocateRequisitionId(),
      docNo: "",
      status: "Draft",
      requestedBy: 17,
      createdAt: new Date().toISOString(),
      lines: request.lines.map((l) => ({ reqLineId: allocateReqLineId(), itemId: l.itemId, qty: l.qty, requiredBy: l.requiredBy })),
    }
    requisition.docNo = `PR-2026-${String(requisition.requisitionId).padStart(5, "0")}`
    mockRequisitions.push(requisition)
    return mockDelay(requisition)
  },

  submit(requisitionId: number): Promise<Requisition> {
    const r = mockRequisitions.find((x) => x.requisitionId === requisitionId)
    if (!r) return Promise.reject(new Error(`Mock requisition ${requisitionId} not found`))
    if (r.status !== "Draft") {
      return Promise.reject(new Error(`${r.docNo} has already been submitted.`))
    }
    r.status = "Submitted"
    return mockDelay(r)
  },
}
