export const CARE_TASK_TYPE_VALUES = ["daily_care", "meal", "medication", "rehab", "inspection", "cleaning", "other"] as const;
export type CareTaskType = (typeof CARE_TASK_TYPE_VALUES)[number];

export const CARE_TASK_PRIORITY_VALUES = ["low", "normal", "high", "urgent"] as const;
export type CareTaskPriority = (typeof CARE_TASK_PRIORITY_VALUES)[number];

export const CARE_TASK_STATUS_VALUES = ["pending", "in_progress", "completed", "cancelled"] as const;
export type CareTaskStatus = (typeof CARE_TASK_STATUS_VALUES)[number];

export const CARE_TASK_TYPE_LABELS: Record<CareTaskType, string> = {
  daily_care: "日常照护",
  meal: "助餐",
  medication: "用药",
  rehab: "康复",
  inspection: "巡检",
  cleaning: "清洁",
  other: "其他",
};

export const CARE_TASK_PRIORITY_LABELS: Record<CareTaskPriority, string> = {
  low: "低",
  normal: "普通",
  high: "高",
  urgent: "紧急",
};

export const CARE_TASK_STATUS_LABELS: Record<CareTaskStatus, string> = {
  pending: "待处理",
  in_progress: "进行中",
  completed: "已完成",
  cancelled: "已取消",
};

export type CareTask = {
  id: string;
  organizationId: string;
  elderId?: string;
  elderName: string;
  title: string;
  careType: CareTaskType;
  priority: CareTaskPriority;
  status: CareTaskStatus;
  scheduledAt: string;
  assigneeLabel: string;
  executionNotes: string;
  completedAt?: string;
  completedByAccountId?: string;
  completedByName?: string;
  createdAt: string;
  updatedAt: string;
};

export type CareExecutionMetrics = {
  pending: number;
  inProgress: number;
  completedToday: number;
  highPriority: number;
};

export type CareExecutionData = {
  metrics: CareExecutionMetrics;
  tasks: CareTask[];
};

export type CareTaskStatusUpdateInput = {
  status: CareTaskStatus;
  executionNotes: string;
};

type ValidationSuccess<T> = {
  success: true;
  data: T;
};

type ValidationFailure = {
  success: false;
  reason: string;
};

export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function readString(source: Record<string, unknown>, key: string): string {
  const value = source[key];
  return typeof value === "string" ? value.trim() : "";
}

function readEnum<T extends string>(value: unknown, values: readonly T[]): T | null {
  return typeof value === "string" ? values.find((item) => item === value) ?? null : null;
}

export function validateCareTaskStatusUpdateInput(value: unknown): ValidationResult<CareTaskStatusUpdateInput> {
  if (!isRecord(value)) {
    return { success: false, reason: "请求数据格式无效" };
  }

  const status = readEnum(value.status, CARE_TASK_STATUS_VALUES);
  if (!status) {
    return { success: false, reason: "护理任务状态无效" };
  }

  return {
    success: true,
    data: {
      status,
      executionNotes: readString(value, "executionNotes"),
    },
  };
}
