import { Injectable } from '@nestjs/common';
import { ClassroomsService } from '../../classrooms/classrooms.service';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tool.types';
import { optionalPositiveInt, optionalString, rejectUnknownKeys } from './tool-input';

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

@Injectable()
export class SearchClassroomsTool implements ToolDef<Input> {
  readonly name = 'search_classrooms';
  readonly skillKey = 'classroom';
  readonly description = '查询教室（名称、楼栋、容量、房型、当前占用状态），不返回排课明细。';
  readonly requiredPermission = 'classroom:view';
  readonly inputSchema = {
    type: 'object',
    properties: {
      keyword: { type: 'string', maxLength: 100, description: '教室名称关键词' },
      building: { type: 'string', maxLength: 50, description: '楼栋' },
      limit: { type: 'integer', minimum: 1, maximum: 50 },
    },
    additionalProperties: false,
  };
  constructor(private readonly service: ClassroomsService) {}

  validate(raw: Record<string, unknown>): ToolInputResult<Input> {
    const invalid = rejectUnknownKeys(raw, ['keyword', 'building', 'limit']);
    if (invalid) return invalid;
    const keyword = optionalString(raw.keyword, 'keyword', 100); if (!keyword.ok) return keyword;
    const building = optionalString(raw.building, 'building', 50); if (!building.ok) return building;
    const limit = optionalPositiveInt(raw.limit, 'limit', 50); if (!limit.ok) return limit;
    return { ok: true, value: { keyword: keyword.value, building: building.value, limit: limit.value } };
  }

  execute(input: Input, _context: AgentToolContext) {
    return this.service.agentSearchClassrooms(input);
  }
}
