import { Injectable } from '@nestjs/common';
import { ClassesService } from '../../classes/classes.service';
import { AgentBusinessScopeFactory } from '../agent-business-scope.factory';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tool.types';
import { optionalPositiveInt, optionalString, rejectUnknownKeys } from './tool-input';

interface Input { keyword?: string; status?: string; limit?: number }

@Injectable()
export class SearchClassesTool implements ToolDef<Input> {
  readonly name = 'search_classes';
  readonly skillKey = 'student';
  readonly description = '查询当前用户有权查看的班级，仅返回班级基础字段和在读人数。';
  readonly requiredPermission = 'class:view';
  readonly inputSchema = { type: 'object', properties: {
    keyword: { type: 'string', maxLength: 100 }, status: { type: 'string', maxLength: 20 },
    limit: { type: 'integer', minimum: 1, maximum: 50 },
  }, additionalProperties: false };
  constructor(private readonly service: ClassesService, private readonly scopes: AgentBusinessScopeFactory) {}
  validate(raw: Record<string, unknown>): ToolInputResult<Input> {
    const invalid = rejectUnknownKeys(raw, ['keyword', 'status', 'limit']); if (invalid) return invalid;
    const keyword = optionalString(raw.keyword, 'keyword', 100); if (!keyword.ok) return keyword;
    const status = optionalString(raw.status, 'status', 20); if (!status.ok) return status;
    const limit = optionalPositiveInt(raw.limit, 'limit', 50); if (!limit.ok) return limit;
    return { ok: true, value: { keyword: keyword.value, status: status.value, limit: limit.value } };
  }
  execute(input: Input, context: AgentToolContext) {
    return this.service.agentSearchClasses(context.userId, this.scopes.canManageAllClasses(context), input);
  }
}
