import { fetchUpdatedAvatars } from '@api/avatars';
import * as FileSystem from 'expo-file-system';
import { storage } from 'src/storage';
import { API_HOST } from 'src/constants';

const dirPath = `${FileSystem.documentDirectory}avatars`;

async function downloadAvatar(userId: number) {
  try {
    const avatarUrl = `${API_HOST}/img/avatars/small/${userId}.webp`;
    let fileUri = `${dirPath}/${userId}.webp`;

    await FileSystem.downloadAsync(avatarUrl, fileUri);
  } catch (error) {
    console.error('Error downloading avatars: ', error);
  }
}

export async function updateAvatars(lastUpdateDate: string) {
  const avatars = await fetchUpdatedAvatars(lastUpdateDate);
  const currentDate = new Date().toISOString().split('T')[0];

  if (avatars && avatars.updated) {
    const dirInfo = await FileSystem.getInfoAsync(dirPath);

    if (!dirInfo.exists) {
      await FileSystem.makeDirectoryAsync(dirPath, { intermediates: true });
    }

    for (const avatar of avatars.updated) {
      await downloadAvatar(avatar);
    }

    storage.set('lastUpdateDate', currentDate);
  }
}
