import { Page } from '@playwright/test';

import { testsConfig } from '../../config';
import { ApiUser, ApiUserAuthKey, ApiUserProfile, User } from '../../types';

export const apiGetUsers = async (page: Page): Promise<ApiUser[]> => {
  const url = testsConfig.CORE_BASE_URL + '/user';
  const users = await page.evaluate(async (url) => {
    return await fetch(url, {
      method: 'GET',
    }).then((res) => res.json());
  }, url);
  return users;
};

export const apiGetUserProfile = async (
  page: Page,
  username: string,
): Promise<ApiUserProfile> => {
  const url = testsConfig.CORE_BASE_URL + '/user/' + username;
  const response = await page.request.get(url, {
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const userProfile = await response.json();
  return userProfile;
};

export const apiGetMe = async (page: Page): Promise<ApiUser> => {
  const url = testsConfig.CORE_BASE_URL + '/me';
  const userData = await page.evaluate(async (url) => {
    return await fetch(url, {
      method: 'GET',
    }).then((res) => res.json());
  }, url);
  return userData;
};

export const apiGetUserAuthKeys = async (
  page: Page,
  username: string,
): Promise<ApiUserAuthKey[]> => {
  const url = testsConfig.CORE_BASE_URL + `/user/${username}/auth_key`;
  const response = await page.request.get(url, {
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const userData = await response.json();
  return userData;
};

export const apiCreateUsersBulk = async (page: Page, users: User[]): Promise<void> => {
  for (const user of users) {
    await apiCreateUser(page, user);
  }
};

export const apiCreateUser = async (page: Page, user: User): Promise<void> => {
  const url = testsConfig.CORE_BASE_URL + '/user';
  await page.request.post(url, {
    data: {
      username: user.username,
      first_name: user.firstName,
      last_name: user.lastName,
      email: user.mail,
      phone: user.phone,
      password: user.password,
    },
    headers: {
      'Content-Type': 'application/json',
    },
  });
};
