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

export interface PostGetProfileData extends ResponseType {
  user_id: number;
  email: string;
  first_name: string;
  last_name: string;
  username: string;
  avatar: string;
  date_of_birth: string;
  homebase: number;
  homebase2: number | null;
  bio: string;
  links: {
    f?: SocialData;
    t?: SocialData;
    i?: SocialData;
    y?: SocialData;
    www?: SocialData;
    other?: SocialData;
  };
}

export interface PostSetProfileData {
  token: string;
  user?: {
    email?: string;
    first_name?: string;
    last_name?: string;
    date_of_birth?: string;
    username?: string;
    homebase?: number;
    homebase2?: number;
    bio?: string;
    f?: string;
    t?: string;
    i?: string;
    y?: string;
    www?: string;
    other?: string;
  };
  photo?: {
    type: string;
    uri: string;
    name: string;
  };
}

export interface PostSetProfileDataReturn extends ResponseType {
  updated: string[];
  not_updated: string[];
}

export type SocialData = {
  link: string;
  active: 0 | 1;
};

export interface PostGetProfileInfoReturn extends ResponseType {
  username: string;
  email: string;
  first_name: string;
  last_name: string;
  date_of_birth: string;
  avatar_full_size: string;
  avatar: string;
  bio: string;
  links: {
    f?: SocialData;
    t?: SocialData;
    i?: SocialData;
    y?: SocialData;
    www?: SocialData;
    other?: SocialData;
  };
  homebase: number;
  homebase_name: string;
  homebase_flag: string;
  homebase2: number;
  homebase2_name: string;
  homebase2_flag: string;
  series: Series[];
  scores: Score[];
}

export type Series = {
  id: number;
  score: number;
  name: string;
  icon_png: string;
};

export type Score = {
  name: string;
  score: number;
};

export const userApi = {
  getProfileData: (token: string) =>
    request.postForm<PostGetProfileData>(API.GET_USER_SETTINGS_DATA, { token }),
  setProfileData: (data: PostSetProfileData) => {
    const formData = new FormData();

    formData.append('token', JSON.stringify(data.token));
    formData.append('user', JSON.stringify(data.user));
    formData.append('photo', {
      ...data.photo
    } as unknown as Blob);

    return request.postForm<PostSetProfileDataReturn>(API.SET_USER_SETTINGS_DATA, formData);
  },
  getProfileInfo: (token: string) =>
    request.postForm<PostGetProfileInfoReturn>(API.PROFILE_INFO, { token }),
  getProfileInfoPublic: (uid: number) =>
    request.postForm<Exclude<PostGetProfileInfoReturn, { email: null }>>(API.PROFILE_INFO_PUBLIC, {
      uid
    })
};
