import * as FileSystem from 'expo-file-system/legacy';
import {
  CACHE_EXPIRATION_DAYS,
  CACHE_MAX_SIZE_MB,
  CACHED_ATTACHMENTS_DIR
} from 'src/constants/constants';

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

export const cleanCache = async () => {
  try {
    const dirInfo = await FileSystem.getInfoAsync(CACHED_ATTACHMENTS_DIR);
    if (!dirInfo.exists) return;

    const files = await FileSystem.readDirectoryAsync(CACHED_ATTACHMENTS_DIR);
    let totalSize = 0;
    const now = Date.now();

    for (const file of files) {
      const filePath = `${CACHED_ATTACHMENTS_DIR}${file}`;
      const fileInfo = await FileSystem.getInfoAsync(filePath);

      if (fileInfo.exists) {
        totalSize += fileInfo.size / (1024 * 1024);
        const fileAgeDays = (now - fileInfo.modificationTime * 1000) / (1000 * 60 * 60 * 24);

        if (fileAgeDays > CACHE_EXPIRATION_DAYS) {
          await FileSystem.deleteAsync(filePath);
        }
      }
    }

    if (totalSize > CACHE_MAX_SIZE_MB) {
      await FileSystem.deleteAsync(CACHED_ATTACHMENTS_DIR, { idempotent: true });
      await FileSystem.makeDirectoryAsync(CACHED_ATTACHMENTS_DIR, { intermediates: true });
    }
  } catch (error) {
    console.error('Error cleaning cache:', error);
  }
};

export async function deleteAvatarsDirectory() {
  try {
    const dirInfo = await FileSystem.getInfoAsync(dirPath);

    if (dirInfo.exists) {
      await FileSystem.deleteAsync(dirPath, { idempotent: true });
    }
  } catch (error) {
    console.error('Error deleting avatars directory: ', error);
  }
}
