interface TaskMutationIdentity {
  currentUserId: string;
  projectManagerUserId?: string | null;
}

/**
 * 判定对象是否处于可编辑/可操作状态。
 *
 * 按按钮可见度矩阵（spec §4.2 / §4.3 注释 `allowEdit === true 即 pending / active 状态`）：
 * 可编辑状态严格 = `pending` OR `active`，**不含 paused / completed / cancelled**。
 *
 * 不用 `record.allowEdit === true`：列表 VO 后端不一定下发该字段，
 * 经 `normalizeProjectExecution` 的 `Boolean(undefined) === false` 会让列表所有行误判为不可编辑。
 * 直接读 `statusCode` 字段（列表 / 详情 VO 都必下发，状态机核心字段）。
 */
export function isMutable(record: { statusCode: string }): boolean {
  return record.statusCode === 'pending' || record.statusCode === 'active';
}

function isTaskMutationActor(task: Api.Project.ProjectTask, identity: TaskMutationIdentity): boolean {
  const { currentUserId, projectManagerUserId } = identity;

  if (!currentUserId) return false;

  return (
    currentUserId === task.ownerId ||
    currentUserId === task.executionOwnerId ||
    (Boolean(projectManagerUserId) && currentUserId === projectManagerUserId)
  );
}

export function isExecutionMutationActor(
  execution: Api.Project.ProjectExecution,
  identity: TaskMutationIdentity
): boolean {
  const { currentUserId, projectManagerUserId } = identity;

  if (!currentUserId) return false;

  return (
    currentUserId === execution.ownerId || (Boolean(projectManagerUserId) && currentUserId === projectManagerUserId)
  );
}

export function canEditExecutionByIdentity(
  execution: Api.Project.ProjectExecution,
  identity: TaskMutationIdentity
): boolean {
  return isMutable(execution) && isExecutionMutationActor(execution, identity);
}

export function canDeleteExecutionByIdentity(
  execution: Api.Project.ProjectExecution,
  identity: TaskMutationIdentity
): boolean {
  if (execution.statusCode === 'completed') return false;
  return isExecutionMutationActor(execution, identity);
}

export function canEditTaskByIdentity(task: Api.Project.ProjectTask, identity: TaskMutationIdentity): boolean {
  return isMutable(task) && isTaskMutationActor(task, identity);
}

export function canDeleteTaskByIdentity(task: Api.Project.ProjectTask, identity: TaskMutationIdentity): boolean {
  if (task.statusCode === 'completed') return false;
  return isTaskMutationActor(task, identity);
}
