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

export interface PostGetPhotosReturn extends ResponseType {
  all_regions: {
    id: number;
    dare: boolean;
    nm: boolean;
    country: string;
    name: string;
    flag: string;
  }[];
  by_date: {
    [key: string]: PhotosData[];
  };
  by_region: {
    id: number;
    country: string;
    name: string | null;
    flag: string;
    nm: boolean;
    dare: boolean;
    photos: PhotosData[];
  }[];
  by_album: {
    album_id: number;
    album_name: string;
    album_cover_photo: string;
    photos: PhotosData[];
  }[];
}

interface PhotosData {
  id: number;
  region_nm: number;
  region_dare: number;
  region: number;
  title: string;
  date: string;
  url_small: string;
  url_mid: string;
  url_full: string;
  album_id: number;
  album_name: string;
}

export interface PostSetTempData {
  token: string;
  file: {
    type: string;
    uri: string;
    name: string;
  };
}

export interface PostSetSaveTemp {
  token: string;
  guids: string[];
  date: string | null;
  region: number;
  description: string | null;
}

export interface PostGetTempReturn extends ResponseType {
  photos: {
    guid: string;
    link: string;
  }[];
}

export interface PostSetTempReturn extends ResponseType {
  guid: string;
  link: string;
}

export interface PostSetSaveTempReturn extends ResponseType {
  saved: string[];
  errors: string[];
}

export interface PostSetUpdatePhoto {
  token: string;
  photo_id: number;
  date: string | null;
  region: number | null;
  description: string | null;
}

export const photosApi = {
  getPhotosForUser: (token: string) =>
    request.postForm<PostGetPhotosReturn>(API.GET_PHOTOS_FOR_USER, { token }),
  setUploadTemp: (data: PostSetTempData) => {
    const formData = new FormData();

    formData.append('token', data.token);
    formData.append('file', {
      ...data.file
    } as unknown as Blob);

    return request.postForm<PostSetTempReturn>(API.UPLOAD_TEMP, formData);
  },
  getTemp: (token: string) => request.postForm<PostGetTempReturn>(API.GET_TEMP, { token }),
  removeTemp: (token: string, guid: string) =>
    request.postForm<ResponseType>(API.REMOVE_TEMP, { token, guid }),
  saveTemp: (data: PostSetSaveTemp) => request.postForm<PostSetSaveTempReturn>(API.SAVE_TEMP, data),
  deletePhoto: (token: string, photo_id: number) =>
    request.postForm<ResponseType>(API.DELETE_PHOTO, { token, photo_id }),
  updatePhoto: (data: PostSetUpdatePhoto) =>
    request.postForm<PostSetSaveTempReturn>(API.UPDATE_PHOTO, data)
};
export { ResponseType };
