// Pure utility library — no server imports. Safe in tests and client components.

export type BacklogItemInput = {
  title: string;
  type: "product" | "portfolio";
  workType: BacklogWorkType;
  status: BacklogStatus;
  source?: BacklogSource;
  priority?: number;
  body?: string;
  taxonomyNodeId?: string;
  digitalProductId?: string;
  epicId?: string;
};

export type BacklogItemWithRelations = {
  id: string;
  itemId: string;
  title: string;
  status: string;
  type: string;
  workType: string | null;
  source: string | null;
  body: string | null;
  priority: number | null;
  epicId: string | null;
  triageOutcome: string | null;
  effortSize: string | null;
  activeBuildId: string | null;
  activeBuild: { buildId: string; phase: string | null } | null;
  digitalProduct: { id: string; productId: string; name: string } | null;
  taxonomyNode: { id: string; nodeId: string; name: string } | null;
  submittedBy: { email: string } | null;
  completedAt: Date | null;
  agentId: string | null;
  createdAt: Date;
  updatedAt: Date;
  upstreamIssueNumber: number | null;
  upstreamIssueUrl: string | null;
};

export type DigitalProductSelect = {
  id: string;
  productId: string;
  name: string;
  lifecycleStage: string;
};

export type TaxonomyNodeSelect = {
  id: string;
  nodeId: string;
  name: string;
};

export type PortfolioForSelect = {
  id: string;
  slug: string;
  name: string;
};

export type EpicInput = {
  title: string;
  description?: string;
  status: "open" | "in-progress" | "done";
  portfolioIds: string[];
};

export type EpicForSelect = {
  id: string;
  epicId: string;
  title: string;
};

export type EpicPortfolioLink = {
  epicId: string;
  portfolioId: string;
  portfolio: { id: string; slug: string; name: string };
};

export type EpicWithRelations = {
  id: string;
  epicId: string;
  title: string;
  description: string | null;
  status: string;
  createdAt: Date;
  updatedAt: Date;
  submittedBy: { email: string } | null;
  agentId: string | null;
  completedAt: Date | null;
  portfolios: EpicPortfolioLink[];
  items: BacklogItemWithRelations[];
};

/** Returns null if valid, or an error message if invalid. */
export function validateBacklogInput(input: BacklogItemInput): string | null {
  if (!input.title.trim()) return "Title is required";
  if (input.type === "product" && !input.digitalProductId) {
    return "A digital product is required for product-type items";
  }
  return null;
}

export const EPIC_STATUSES = ["open", "in-progress", "done"] as const;
export type EpicStatus = typeof EPIC_STATUSES[number];

export const BACKLOG_STATUS_VALUES = [
  "triaging",
  "open",
  "in-progress",
  "done",
  "deferred",
] as const;
export type BacklogStatus = (typeof BACKLOG_STATUS_VALUES)[number];

export const BACKLOG_TRIAGE_OUTCOMES = [
  "build",
  "runbook",
  "coworker-task",
  "defer",
  "duplicate",
  "discard",
] as const;
export type BacklogTriageOutcome = (typeof BACKLOG_TRIAGE_OUTCOMES)[number];

// Pure intake-origin enum. The previous mixed-axis values
// (feature-gap, bug, tool-gap, skill-gap, doc-gap) moved into
// BACKLOG_WORK_TYPE_VALUES below; this enum now answers "how did it arrive"
// not "what kind of work is it".
//
// New values are added only when a writer needs them
// (single-source-of-truth + YAGNI).
export const BACKLOG_SOURCE_VALUES = [
  "user-request",
  "automated-detection",
] as const;
export type BacklogSource = (typeof BACKLOG_SOURCE_VALUES)[number];

// Closed work-type enum (the WHAT). Required on every new BacklogItem.
// Aligned with the Conventional Commits subset that maps cleanly to today's
// BI consumers: bug == fix, feature == feat, plus chore | doc | tool | skill |
// refactor. perf | test | security | ci | style | revert are deferred until a
// writer needs them.
//
// Adding a value requires updating this enum AND the mirror in
// apps/web/lib/mcp-tools.ts (create_backlog_item, update_backlog_item,
// list_backlog_items) in the same commit per AGENTS.md §3.
export const BACKLOG_WORK_TYPE_VALUES = [
  "bug",
  "feature",
  "chore",
  "doc",
  "tool",
  "skill",
  "refactor",
] as const;
export type BacklogWorkType = (typeof BACKLOG_WORK_TYPE_VALUES)[number];

export const BACKLOG_EFFORT_SIZES = ["small", "medium", "large", "xlarge"] as const;
export type BacklogEffortSize = (typeof BACKLOG_EFFORT_SIZES)[number];

/** Returns null if valid, or an error message if invalid. */
export function validateEpicInput(input: EpicInput): string | null {
  if (!input.title.trim()) return "Title is required";
  if (!(EPIC_STATUSES as readonly string[]).includes(input.status)) return "Invalid status";
  return null;
}

/** Status badge colours (inline styles). */
export const BACKLOG_STATUS_COLOURS: Record<string, string> = {
  "open":        "#38bdf8",
  "in-progress": "#fb923c",
  "done":        "#4ade80",
  "deferred":    "#8888a0",
};

/** Epic status badge colours (inline styles). */
export const EPIC_STATUS_COLOURS: Record<string, string> = {
  "open":        "#38bdf8",
  "in-progress": "#fb923c",
  "done":        "#4ade80",
};

/** Human-readable labels for CSDM lifecycle stages. */
export const LIFECYCLE_STAGE_LABELS: Record<string, string> = {
  plan:       "Plan",
  design:     "Design",
  build:      "Build",
  production: "Production",
  retirement: "Retirement",
};

/** Human-readable labels for CSDM lifecycle statuses. */
export const LIFECYCLE_STATUS_LABELS: Record<string, string> = {
  draft:    "Draft",
  active:   "Active",
  inactive: "Inactive",
};
