import { Injectable } from '@nestjs/common';
import { ToolExecutionResult, ToolDefinition, ToolContext } from './tool.types';
import { LokiClient } from '../../outbound/loki/loki.client';

type LokiEppRiskLogsArgs = {
  start?: string;
  end?: string;
  step?: string;
  limit?: number;
};

const EPP_RISK_LOGS_QUERY =
  '{service="ahnlab_epp", syslog_type="V3_MALWARE"} | json | line_format "{{.host}} | {{.src_ip}} | {{.login_id}} | {{.message}}"';

@Injectable()
export class LokiEppRiskLogsUsecase {
  constructor(private readonly lokiClient: LokiClient) {}

  definition(): ToolDefinition {
    return {
      name: 'loki.epp_risk_logs',
      description: 'Fetch EPP V3_MALWARE logs (host | src_ip | login_id | message) from Loki.',
      inputSchema: {
        type: 'object',
        properties: {
          start: { type: 'string', description: 'RFC3339 or epoch' },
          end: { type: 'string', description: 'RFC3339 or epoch' },
          step: { type: 'string', description: 'e.g. 10s, 1m' },
          limit: { type: 'integer', minimum: 1, maximum: 5000 },
        },
        additionalProperties: false,
      },
      handler: async (args, context) => this.execute(args, context),
    };
  }

  async execute(args: unknown, _context: ToolContext): Promise<ToolExecutionResult> {
    const typedArgs = (args ?? {}) as LokiEppRiskLogsArgs;

    try {
      const payload = await this.lokiClient.queryRange({
        query: EPP_RISK_LOGS_QUERY,
        start: typedArgs.start,
        end: typedArgs.end,
        step: typedArgs.step,
        limit: typedArgs.limit,
      });

      return {
        output: [
          {
            kind: 'text',
            text: JSON.stringify(payload, null, 2),
          },
        ],
        isError: false,
      };
    } catch (error) {
      const details = error instanceof Error ? error.message : String(error);
      return {
        output: [{ kind: 'text', text: `loki.epp_risk_logs failed: ${details}` }],
        isError: true,
      };
    }
  }
}
