import { computed } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { useObjectContextStore } from '@/store/modules/object-context';
import {
  canDeleteExecutionByIdentity,
  canDeleteTaskByIdentity,
  canEditExecutionByIdentity,
  canEditTaskByIdentity,
  isExecutionMutationActor,
  isMutable
} from './task-permission-rules';

/**
 * 任务 / 执行按钮可见度集中判定
 *
 * 关键领域规则：
 * - 任务编辑 / 删除入口先按身份收口：任务负责人、任务所属执行负责人、项目负责人
 * - 权限码只作为后端最终校验的兜底，不单独决定前端按钮可见度
 * - 本人能做的：状态推进（含 cancel "退出"任务）、加协办人、在自己任务下新增子任务
 * - 执行负责人能维护一级任务协办人（一级任务 `executionOwnerId` 通道；子任务不开此通道）
 *
 * 权限码来源：`project:*` / `project:execution:*` / `project:task:*` 是**对象域权限码**，
 * 挂在项目对象上下文里（项目负责人 / 项目协作者等角色），从 objectContextStore.buttonCodes 取，
 * **不在** authStore.userInfo.buttons（那是全局站点级权限）。
 */
export function useTaskPermissions() {
  const authStore = useAuthStore();
  const objectContextStore = useObjectContextStore();

  const currentUserId = computed(() => authStore.userInfo.userId || '');
  const buttonCodeSet = computed(() => new Set(objectContextStore.buttonCodes));
  const currentProjectManagerUserId = computed(() => {
    const summary = objectContextStore.objectSummary as Api.Project.ProjectContext | null;
    return summary?.currentProject?.managerUserId || null;
  });

  function hasPermission(code: string): boolean {
    return buttonCodeSet.value.has(code);
  }

  // —— 执行侧 ——

  function canEditExecution(execution: Api.Project.ProjectExecution): boolean {
    return canEditExecutionByIdentity(execution, {
      currentUserId: currentUserId.value,
      projectManagerUserId: currentProjectManagerUserId.value
    });
  }

  function canDeleteExecution(execution: Api.Project.ProjectExecution): boolean {
    // completed 终态后端硬卡（不允许主动删，级联删除时由后端兜底），前端按钮也拦掉
    return canDeleteExecutionByIdentity(execution, {
      currentUserId: currentUserId.value,
      projectManagerUserId: currentProjectManagerUserId.value
    });
  }

  /** 协办人弹窗内的写操作（设为负责人 / 失效 / 新增协办人）与编辑同一身份口径：执行负责人或项目负责人 */
  function canChangeExecutionOwner(execution: Api.Project.ProjectExecution): boolean {
    return (
      isMutable(execution) &&
      isExecutionMutationActor(execution, {
        currentUserId: currentUserId.value,
        projectManagerUserId: currentProjectManagerUserId.value
      })
    );
  }

  function canManageExecutionAssignee(execution: Api.Project.ProjectExecution): boolean {
    return (
      isMutable(execution) &&
      isExecutionMutationActor(execution, {
        currentUserId: currentUserId.value,
        projectManagerUserId: currentProjectManagerUserId.value
      })
    );
  }

  /**
   * 协办人入口按钮（列表面板）是否显示。
   *
   * 仅"项目负责人 / 项目创建人 / 执行负责人"可见，普通登录用户隐藏（去"查看"对话框里看团队）。
   * 不含状态前置——任何状态下身份匹配都给入口；dialog 内的"加 / 移 / 换 owner"写按钮自己再判 isMutable。
   */
  function canSeeExecutionAssigneeEntry(execution: Api.Project.ProjectExecution): boolean {
    return (
      hasPermission('project:execution:assignee') ||
      hasPermission('project:execution:owner') ||
      currentUserId.value === execution.ownerId
    );
  }

  // —— 任务侧（按一级 / 子任务指派） ——

  function isTopLevelTask(task: Api.Project.ProjectTask): boolean {
    return task.parentTaskId === null || task.parentTaskId === undefined;
  }

  function canEditTask(task: Api.Project.ProjectTask): boolean {
    return canEditTaskByIdentity(task, {
      currentUserId: currentUserId.value,
      projectManagerUserId: currentProjectManagerUserId.value
    });
  }

  function canDeleteTask(task: Api.Project.ProjectTask): boolean {
    return canDeleteTaskByIdentity(task, {
      currentUserId: currentUserId.value,
      projectManagerUserId: currentProjectManagerUserId.value
    });
  }

  function canCreateTopLevelTask(execution: Api.Project.ProjectExecution): boolean {
    return isMutable(execution) && (hasPermission('project:task:create') || currentUserId.value === execution.ownerId);
  }

  function canCreateSubTask(task: Api.Project.ProjectTask): boolean {
    return isMutable(task) && (hasPermission('project:task:create') || currentUserId.value === task.ownerId);
  }

  function canManageTaskAssignee(task: Api.Project.ProjectTask): boolean {
    if (!isMutable(task)) return false;
    if (hasPermission('project:task:assignee')) return true;
    if (currentUserId.value === task.ownerId) return true;
    // 一级任务：执行负责人也可维护协办人；子任务：父任务负责人不在此放行（§4.2）
    return isTopLevelTask(task) && currentUserId.value === task.executionOwnerId;
  }

  return {
    // execution
    canEditExecution,
    canDeleteExecution,
    canChangeExecutionOwner,
    canManageExecutionAssignee,
    canSeeExecutionAssigneeEntry,
    // task
    canEditTask,
    canDeleteTask,
    canCreateTopLevelTask,
    canCreateSubTask,
    canManageTaskAssignee
  };
}
