export type Value = "yes" | "no";
export type Status = "pending" | "no" | "yes";
export interface ChainInput { dropout?: Value | undefined; completion?: Value | undefined; certification?: Value | undefined; placement?: Value | undefined; locality?: Value | undefined; retention?: Value | undefined }
export type ChainKey = Exclude<keyof ChainInput, "dropout">;
export interface Derived { status: Status; source: string | null }

/** What each result needs first. A "no" there settles everything after it. */
const NEEDS: [ChainKey, ChainKey | null][] = [
  ["completion", null], ["certification", "completion"], ["placement", "certification"], ["locality", "placement"], ["retention", "placement"],
];
const LABEL: Record<string, string> = { completion: "derived_completion", certification: "derived_certification", placement: "derived_placement" };

/**
 * One status per trainee for every indicator. A reported value always wins. Where nothing was reported:
 * a reported dropout makes every later status "no"; a "no" in a required earlier step makes the later steps "no";
 * otherwise it stays "pending" until the provider reports it.
 */
export function deriveChain(input: ChainInput): Record<ChainKey, Derived> {
  const out = {} as Record<ChainKey, Derived>;
  for (const [key, needs] of NEEDS) {
    const reported = input[key];
    const before = needs ? out[needs] : undefined;
    if (reported) out[key] = { status: reported, source: "tp_reported" };
    else if (input.dropout === "yes") out[key] = { status: "no", source: "derived_dropout" };
    else if (before?.status === "no") out[key] = { status: "no", source: LABEL[needs!] ?? null };
    else out[key] = { status: "pending", source: null };
  }
  return out;
}
