import * as FileSystem from 'expo-file-system/legacy';

export const fileSystemUtils = {
  /**
   * Saves a temporary media file (e.g. image captured from camera) to the persistent document directory.
   */
  async saveImageToLocal(tempUri: string, filename: string): Promise<string> {
    const targetDir = `${FileSystem.documentDirectory}media/`;
    
    // Ensure target folder exists
    const dirInfo = await FileSystem.getInfoAsync(targetDir);
    if (!dirInfo.exists) {
      await FileSystem.makeDirectoryAsync(targetDir, { intermediates: true });
    }
    
    const destUri = `${targetDir}${filename}`;
    await FileSystem.copyAsync({
      from: tempUri,
      to: destUri
    });
    
    return destUri;
  },

  /**
   * Deletes a local file if it exists.
   */
  async deleteLocalFile(uri: string): Promise<void> {
    try {
      const fileInfo = await FileSystem.getInfoAsync(uri);
      if (fileInfo.exists) {
        await FileSystem.deleteAsync(uri);
      }
    } catch (error) {
      console.warn('Lỗi khi xóa tệp tin cục bộ:', error);
    }
  }
};
