// One typed client method per production-template endpoint (docs/30-BACKEND-PHASE2.md §D.1,
// FR-MFG-01..07). ETag/If-Match on update, PATCH status for deactivate (templates are
// deactivated, never hard-deleted, FR-MFG-01).
//
// Note that `update` replaces the WHOLE graph, and that the server's stage/output keys are
// load-bearing: a key it recognises is diffed in place (so historical runs stay linked to the
// stage), while anything else — a `tmp-<uuid>` from the canvas — is inserted. The builder holds
// those keys as React Flow node ids and echoes them back; see the [id]/types.ts header.
import { apiRequest, apiRequestWithETag, buildQuery } from "@/lib/api-client"
import { ApiResult, PagedResponse } from "@/types/common"
import {
  ProductionTemplateGraph,
  ProductionTemplateSummary,
  SaveTemplateRequest,
  TemplateStatus,
} from "@/types/production"

export interface ListTemplatesParams {
  page?: number
  pageSize?: number
  q?: string
  status?: TemplateStatus
  sort?: string
}

export const productionTemplatesApi = {
  list(params: ListTemplatesParams = {}): Promise<PagedResponse<ProductionTemplateSummary>> {
    return apiRequest<PagedResponse<ProductionTemplateSummary>>(`/production-templates${buildQuery(params)}`)
  },

  get(templateId: number): Promise<ApiResult<ProductionTemplateGraph>> {
    return apiRequestWithETag<ProductionTemplateGraph>(`/production-templates/${templateId}`)
  },

  create(request: SaveTemplateRequest): Promise<ApiResult<ProductionTemplateGraph>> {
    return apiRequestWithETag<ProductionTemplateGraph>("/production-templates", {
      method: "POST",
      body: request,
    })
  },

  /** Full-graph replace. `409 TEMPLATE_IN_USE` while any run of this template is InProgress. */
  update(
    templateId: number,
    request: SaveTemplateRequest,
    ifMatch: string,
  ): Promise<ApiResult<ProductionTemplateGraph>> {
    return apiRequestWithETag<ProductionTemplateGraph>(`/production-templates/${templateId}`, {
      method: "PUT",
      body: request,
      ifMatch,
    })
  },

  updateStatus(templateId: number, status: TemplateStatus): Promise<void> {
    return apiRequest<void>(`/production-templates/${templateId}/status`, {
      method: "PATCH",
      body: { status },
    })
  },
}
