import type { bulkAddressUploads } from "@/app/db/schema/bulk_address_uploads";

export const BULK_UPLOAD_STATUSES = [
  "ready_for_processing",
  "mapping_complete",
  "processing",
  "combining",
  "awaiting_review",
  // In-flight state of the async finaliser (ADR-0005); mirrors `combining`. The
  // status column is free text, so no enum migration is needed. UI renders this
  // as "Uploading to ARA" — see STATUS_LABELS.
  "finalising",
  "complete",
  "failed",
] as const;

export type BulkUploadStatus = (typeof BULK_UPLOAD_STATUSES)[number];

export type BulkUpload = typeof bulkAddressUploads.$inferSelect;

// sub_task.service values. NULL is treated as address (legacy rows + the
// backend-spawned postcode-split children, which don't set it). See ADR-0003.
export const SUBTASK_SERVICE = {
  address: "address2uprn",
  classifier: "landlord_description_overrides",
  finaliser: "bulk_upload_finaliser",
} as const;

// User-facing label for a BulkUpload status. The persisted enum value stays
// canonical (`finalising`); the product surface for that state is "Uploading to
// ARA" (ADR-0005 — a display-layer label, never the enum name).
export const STATUS_LABELS: Record<string, string> = {
  ready_for_processing: "Ready for processing",
  mapping_complete: "Mapping complete",
  processing: "Processing",
  combining: "Combining",
  awaiting_review: "Awaiting review",
  finalising: "Uploading to ARA",
  complete: "Complete",
  failed: "Failed",
};

export function statusLabel(status: string): string {
  return STATUS_LABELS[status] ?? status;
}

export type TaskSummary = {
  id: string;
  taskSource: string;
  status: string;
  service: string | null;
  jobStarted: Date | null;
  jobCompleted: Date | null;
  updatedAt: Date;
  totalSubtasks: number;
  completedSubtasks: number;
  failedSubtasks: number;
  // Per-pipeline breakdown so onboarding progress can separate address
  // matching from landlord classification (ADR-0003).
  addressTotal: number;
  addressCompleted: number;
  addressFailed: number;
  classifierTotal: number;
  classifierCompleted: number;
  classifierFailed: number;
};

export type ProgressView = {
  upload: BulkUpload;
  task: TaskSummary | null;
};

const TERMINAL_UPLOAD_STATUSES: ReadonlySet<BulkUploadStatus> = new Set([
  "complete",
  "failed",
]);

export function isTerminalStatus(status: string): boolean {
  return TERMINAL_UPLOAD_STATUSES.has(status as BulkUploadStatus);
}
