import { request } from '../../../utils';
import { API } from '../../../types';
import { ResponseType } from '../response-type';

import { UserRegistrationData, UserResetPasswordData, JoinTestTypes } from './queries';

export interface PostLoginUserReturn extends ResponseType {
  token: string;
  uid: string;
}

export interface PostRegisterUserReturn extends ResponseType {
  token: string; // TODO: optional
  uid: string;
  mail: 1 | 0;
}

export interface UserResetPasswordReturn extends ResponseType {}

export interface UserJoinTestReturn extends ResponseType {
  field: 'USERNAME USED' | 'EMAIL USED';
}

export const authApi = {
  loginUser: (data: { login: string; pass: string }) =>
    request.postForm<PostLoginUserReturn>(API.LOGIN, data),
  registerUser: (data: UserRegistrationData) => {
    const formData = new FormData();

    formData.append('user', JSON.stringify(data.user));
    if (data.photo && data.photo?.uri) {
      formData.append('photo', {
        type:
          data.photo.type === 'image'
            ? data.photo.type + '/' + data.photo.uri.split('.').pop()!
            : data.photo.type,
        uri: data.photo.uri,
        name: data.photo.name
      } as unknown as Blob);
    }

    return request.postForm<PostRegisterUserReturn>(API.REGISTER, formData);
  },
  resetPassword: (data: UserResetPasswordData) =>
    request.postForm<UserResetPasswordReturn>(API.RESET_PASSWORD, data),
  joinTest: (data: JoinTestTypes) => request.postForm<UserJoinTestReturn>(API.JOIN_TEST, data)
};
