import type { Job } from "./schema";

export type DueState =
  | { kind: "none" }
  | { kind: "future"; days: number }
  | { kind: "soon"; days: number }
  | { kind: "today" }
  | { kind: "overdue"; days: number };

const MS_PER_DAY = 24 * 60 * 60 * 1000;

/**
 * Bucket a job's due date into a UI-friendly label.
 *   - none     → no due date
 *   - future   → more than 3 days away
 *   - soon     → 1-3 days away (warn)
 *   - today    → today (warn)
 *   - overdue  → past, work isn't delivered (error)
 *
 * Cancelled or delivered jobs always resolve to 'none' — nothing to warn
 * about once the case is closed.
 */
export function dueState(
  job: Pick<Job, "dueDate" | "status">,
  now: Date = new Date(),
): DueState {
  if (!job.dueDate) return { kind: "none" };
  if (job.status === "delivered" || job.status === "cancelled") {
    return { kind: "none" };
  }
  const due = new Date(job.dueDate);
  // Compare at day granularity so a deadline at 23:59 isn't 'overdue' a
  // few seconds in.
  const dueDay = Date.UTC(due.getUTCFullYear(), due.getUTCMonth(), due.getUTCDate());
  const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
  const diffDays = Math.round((dueDay - today) / MS_PER_DAY);
  if (diffDays < 0) return { kind: "overdue", days: Math.abs(diffDays) };
  if (diffDays === 0) return { kind: "today" };
  if (diffDays <= 3) return { kind: "soon", days: diffDays };
  return { kind: "future", days: diffDays };
}

export function dueLabel(state: DueState): string {
  switch (state.kind) {
    case "overdue":
      return state.days === 1 ? "1 gün gecikti" : `${state.days} gün gecikti`;
    case "today":
      return "Bugün teslim";
    case "soon":
      return state.days === 1 ? "Yarın teslim" : `${state.days} gün kaldı`;
    case "future":
      return `${state.days} gün kaldı`;
    case "none":
      return "";
  }
}
