import { BadRequestException, Injectable } from '@nestjs/common';
import { HttpService } from './http.service';
import { RedisService } from './redis.service';
import { ConfigService } from '@nestjs/config';

const configService = new ConfigService();

@Injectable()
export class ShortenService {
    constructor(
      private readonly httpService: HttpService,
      private readonly redisService: RedisService
    ) {}

    async getTokenShortUrl() {
      let request_token = await this.redisService.get(`shorten_url:token`);
      if (!request_token) {
        const request = await this.httpService.sendRequest(
          'post',
          configService.get('URL_SHORTENER_URL') + `/api/login`,
          {},
          {
              username: configService.get('URL_SHORTENER_USERNAME'),
              password: configService.get('URL_SHORTENER_PASSWORD'),
          },
          false
        );
        request_token = request?.data;

        await this.redisService.set(`shorten_url:token`, request?.data, 60 * 60 * 24);
      }

      return request_token.token;
    }

    async getShortUrl(title, full) {
      let cacheToken = await this.getTokenShortUrl();

      const request = await this.httpService.sendRequest(
        'post',
        configService.get('URL_SHORTENER_URL') + `/api/short_url`,
        {
          headers: {
              Authorization: `Bearer ${cacheToken}`,
          },
        },
        {
          title,
          full,
        }
      );

      return request.data.url;
    }
}
