import { Injectable } from '@nestjs/common';
import ky from 'ky';
import urlcat from 'urlcat';

@Injectable()
export class AuthService {
  public async getAccessToken() {
    const form = new FormData();
    form.append('grant_type', 'password');
    form.append('username', process.env.user);
    form.append('password', process.env.password);

    try {
      const params = new URLSearchParams();
      params.append('grant_type', 'password');
      params.append('username', process.env.user);
      params.append('password', process.env.password);
      const URL = `${process.env.host}${process.env.tokenURL}`;

      const response = await ky
        .post(URL, {
          body: params.toString(),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: 'Basic YWRtaW4tY2xpOnE0RmJnazFkd0NaelFQZmt5VzhhM3NnckV5UHZlRUY3',
          },
        })
        .json();
      return (<any>response).access_token;
    } catch (error) {
      if (error.name === 'HTTPError') {
        const errorJson = await error.response.json();
        console.error('Fehlerantwort vom Server:', errorJson);
      } else {
        console.error('Allgemeiner Fehler:', error);
      }
    }
  }

  public async getUsers() {
    const token = await this.getAccessToken();
    const URL = `${process.env.host}${process.env.usersURL}`;
    const response = await ky
      .get(URL, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `Bearer ${token}`,
        },
      })
      .json();
    return response;
  }
  public async getUser(userid: string) {
    const token = await this.getAccessToken();
    const URL = urlcat(process.env.host, process.env.userURL, { userid });
    const response = await ky
      .get(URL, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `Bearer ${token}`,
        },
      })
      .json();
    return response;
  }
  public async getGroups() {
    const token = await this.getAccessToken();
    const URL = `${process.env.host}${process.env.groupsURL}`;
    const response = await ky
      .get(URL, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `Bearer ${token}`,
        },
      })
      .json();
    return response;
  }

  public async getGroupsForUser(userid: string) {
    const token = await this.getAccessToken();
    const URL = urlcat(process.env.host, process.env.userGroupsURL, { userid });
    const response = await ky
      .get(URL, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `Bearer ${token}`,
        },
      })
      .json();
    return response;
  }
  public async getLastLogin(userid: string) {
    const token = await this.getAccessToken();
    const URL = urlcat(process.env.host, process.env.lastLoginURL, { userid });
    const response = await ky
      .get(URL, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `Bearer ${token}`,
        },
      })
      .json();
    return response;
  }
  public async addUser2Group(userid: string, groupid: string) {
    const token = await this.getAccessToken();
    const URL = urlcat(process.env.host, process.env.addUser2GroupURL, { userid, groupid });
    const response = await ky
      .put(URL, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `Bearer ${token}`,
        },
      })
      .json();
    return response;
  }
}
