/**
 * 作业状态机（纯函数）
 *
 * 状态流转（ISSUE-003 仲裁 scheme A）：
 *   assigned → submitted → graded
 *
 * SubmissionStatus（学生提交维度）：
 *   not_submitted → submitted → graded
 */
export type HomeworkStatus = "assigned" | "submitted" | "graded";

export type HomeworkAction = "submit" | "grade";

const TRANSITIONS: Record<
  HomeworkStatus,
  Partial<Record<HomeworkAction, HomeworkStatus>>
> = {
  assigned: { submit: "submitted" },
  submitted: { grade: "graded" },
  graded: {},
};

export function canTransition(
  from: HomeworkStatus,
  action: HomeworkAction,
): boolean {
  return TRANSITIONS[from]?.[action] !== undefined;
}

export function transition(
  from: HomeworkStatus,
  action: HomeworkAction,
): HomeworkStatus {
  const next = TRANSITIONS[from]?.[action];
  if (!next) {
    throw new Error(
      `Invalid homework state transition: ${from} --${action}-->`,
    );
  }
  return next;
}

export function isTerminal(status: HomeworkStatus): boolean {
  return status === "graded";
}

// SubmissionStatus 状态机（用于 exam_submissions / homework_submissions 表的 status 字段）
export type SubmissionStatus = "not_submitted" | "submitted" | "graded";

export type SubmissionAction = "submit" | "grade";

const SUBMISSION_TRANSITIONS: Record<
  SubmissionStatus,
  Partial<Record<SubmissionAction, SubmissionStatus>>
> = {
  not_submitted: { submit: "submitted" },
  submitted: { grade: "graded" },
  graded: {},
};

export function canTransitionSubmission(
  from: SubmissionStatus,
  action: SubmissionAction,
): boolean {
  return SUBMISSION_TRANSITIONS[from]?.[action] !== undefined;
}

export function transitionSubmission(
  from: SubmissionStatus,
  action: SubmissionAction,
): SubmissionStatus {
  const next = SUBMISSION_TRANSITIONS[from]?.[action];
  if (!next) {
    throw new Error(
      `Invalid submission state transition: ${from} --${action}-->`,
    );
  }
  return next;
}

export const HOMEWORK_STATUSES: readonly HomeworkStatus[] = [
  "assigned",
  "submitted",
  "graded",
] as const;

export const SUBMISSION_STATUSES: readonly SubmissionStatus[] = [
  "not_submitted",
  "submitted",
  "graded",
] as const;
