import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { UserExtendedDTO } from '../dto/user-extended-dto';
import { ApiError } from '../error/api-error';

@Injectable()
export class AuthApiService {
  constructor(private _configService: ConfigService) {}

  async callMethod<T>(method: string, args: any = {}): Promise<T> {
    const host = this._configService.get('integration.authApiHost');
    const key = this._configService.get('integration.authApiKey');

    const response = await axios.post<T>(
      host + method,
      {
        ...args,
        apiKey: key,
      },
      {
        headers: {
          'Content-Type': 'application/json',
        },
        validateStatus: () => true,
      },
    );

    if (response.status !== 200 && response.status !== 201) {
      const res = response.data as any;
      throw new ApiError(res.message, res.code, res.payload);
    }

    return response.data;
  }

  async getUserInfoByid(userId: number): Promise<UserExtendedDTO | null> {
    return (
      await this.callMethod<{ result: UserExtendedDTO | null }>(
        'auth/serviceGetUserInfoByid',
        {
          userId,
        },
      )
    ).result;
  }
}
