import { Injectable } from '@nestjs/common';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tools/agent-tool.types';
import { rejectUnknownKeys } from '../agent-tools/tools/tool-input';
import { BUSINESS_WORKFLOW_KEYS } from './business-context.registry';
import { PendingTasksService } from './pending-tasks.service';

interface GetPendingTasksInput {
  workflowKey?: string;
}

/**
 * 让 Agent 查询业务完成度（未分班、未入住、未出账单、临期租赁等），
 * 用于核实前置数据与给出有数据支撑的下一步建议。
 */
@Injectable()
export class GetPendingTasksTool implements ToolDef<GetPendingTasksInput> {
  readonly name = 'get_pending_tasks';
  readonly skillKey = 'overview';
  readonly requiredPermission = 'ai:chat:use';
  readonly description =
    '获取当前账号可见范围内的业务待办计数（未分班学生、已建档未入住学生、在住未生成账单、租赁缺合同/临期到期等）。写入或导入前用它核实前置数据是否齐备，完成后用它判断后续待办。';
  readonly inputSchema = {
    type: 'object',
    properties: {
      workflowKey: {
        type: 'string',
        description: '可选：聚焦某个闭环（student_teaching / dormitory_billing / classroom_rental）',
        enum: [...BUSINESS_WORKFLOW_KEYS],
      },
    },
    additionalProperties: false,
  };

  constructor(private readonly service: PendingTasksService) {}

  validate(input: Record<string, unknown>): ToolInputResult<GetPendingTasksInput> {
    const invalid = rejectUnknownKeys(input, ['workflowKey']);
    if (invalid) return invalid;
    if (input.workflowKey === undefined) return { ok: true, value: {} };
    if (
      typeof input.workflowKey !== 'string' ||
      !(BUSINESS_WORKFLOW_KEYS as readonly string[]).includes(input.workflowKey)
    ) {
      return { ok: false, error: `workflowKey 必须是 ${BUSINESS_WORKFLOW_KEYS.join(' / ')} 之一` };
    }
    return { ok: true, value: { workflowKey: input.workflowKey } };
  }

  execute(input: GetPendingTasksInput, context: AgentToolContext): Promise<unknown> {
    return this.service.getPendingTasks(context, input.workflowKey);
  }
}
