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

interface Input { classId?: number; classroomId?: number; weekDay?: number; limit?: number }

@Injectable()
export class SearchSchedulesTool implements ToolDef<Input> {
  readonly name = 'search_schedules';
  readonly skillKey = 'student';
  readonly description = '查询当前用户有权查看的排课（班级、教室、星期、节次、教师、起止日期）。';
  readonly requiredPermission = 'schedule:view';
  readonly inputSchema = {
    type: 'object',
    properties: {
      classId: { type: 'integer', minimum: 1, description: '班级ID' },
      classroomId: { type: 'integer', minimum: 1, description: '教室ID' },
      weekDay: { type: 'integer', minimum: 1, maximum: 7, description: '星期（1-7）' },
      limit: { type: 'integer', minimum: 1, maximum: 50 },
    },
    additionalProperties: false,
  };
  constructor(
    private readonly service: SchedulesService,
    private readonly scopes: AgentBusinessScopeFactory,
  ) {}

  validate(raw: Record<string, unknown>): ToolInputResult<Input> {
    const invalid = rejectUnknownKeys(raw, ['classId', 'classroomId', 'weekDay', 'limit']);
    if (invalid) return invalid;
    const classId = optionalPositiveInt(raw.classId, 'classId'); if (!classId.ok) return classId;
    const classroomId = optionalPositiveInt(raw.classroomId, 'classroomId');
    if (!classroomId.ok) return classroomId;
    const weekDay = optionalPositiveInt(raw.weekDay, 'weekDay');
    if (!weekDay.ok) return weekDay;
    if (weekDay.value !== undefined && weekDay.value > 7) {
      return { ok: false, error: 'weekDay 必须在 1-7 之间' };
    }
    const limit = optionalPositiveInt(raw.limit, 'limit', 50); if (!limit.ok) return limit;
    return {
      ok: true,
      value: {
        classId: classId.value,
        classroomId: classroomId.value,
        weekDay: weekDay.value,
        limit: limit.value,
      },
    };
  }

  execute(input: Input, context: AgentToolContext) {
    return this.service.agentSearchSchedules(
      context.userId,
      this.scopes.canManageAllClasses(context),
      input,
    );
  }
}
