import { Injectable } from '@nestjs/common';
import { DepositsService } from '../../deposits/deposits.service';
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 SearchDepositsTool implements ToolDef<Input> {
  readonly name = 'search_deposits';
  readonly skillKey = 'billing';
  readonly description = '查询押金记录（学生姓名/学号、金额、状态、退款信息）。';
  readonly requiredPermission = 'deposit:view';
  readonly inputSchema = {
    type: 'object',
    properties: {
      keyword: { type: 'string', maxLength: 100, description: '学生姓名或学号' },
      status: { type: 'string', maxLength: 20, description: '押金状态' },
      limit: { type: 'integer', minimum: 1, maximum: 50 },
    },
    additionalProperties: false,
  };
  constructor(private readonly service: DepositsService) {}

  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.agentSearchDeposits(input);
  }
}
