import { Injectable } from '@severo-tech/injection-decorator';
import { BadGateway } from '@somma/node-errors';
import cache from 'node-cache-decorator';
import axios, { isAxiosError } from 'axios';
import {
  IAgentClient,
  IAgentClientFilter,
} from '../../application/contracts';
import { Base01EUSTClient } from './base-01eust-client';
import { RetryMethod } from '../../application/decorators';
import { Agent } from '../../domain/agent';
import { IPagination } from '../../domain/pagination';

@Injectable()
export class Agent01EUSTClient extends Base01EUSTClient implements IAgentClient {
  @RetryMethod({ ms: 500 })
  @cache('Agent01EUSTClient.find', 60 * 60)
  public async find(filters: IAgentClientFilter, limit = 50, offset = 1): Promise<Agent[]> {
    const url = `${this.baseURL}/v1/agents`;

    const params = {
      ...filters,
      limit,
      offset,
    };

    const headers = {
      Authorization: await this.getToken(),
    };

    this.logger.debug(
      `"Agent01EUSTClient.find" - Sending GET request to url [${url}] with params [${JSON.stringify(params)}]`,
    );

    try {
      const { data: response } = await axios.get<IPagination<Agent[]>>(url, {
        params,
        headers,
      });

      if (response.count > limit * offset) {
        const aggregation = await this.find(filters, limit, offset + 1);
        return [...response.data, ...aggregation];
      }

      return response.data;
    } catch (error) {
      const message = `Cannot get Agents: GET - "${url}" | params: [${JSON.stringify(params)}]`;
      const err = isAxiosError(error) ? error.response?.data : error;
      this.logger.error(message, err);
      throw new BadGateway(message, undefined, err);
    }
  }
}
