import 'dart:io';
import 'package:media_store_plus/media_store_plus.dart';

Future<String> saveReportFile({
  required String fileName,
  required List<int> bytes,
  String? mimeType,
}) async {
  final tempDir = Directory.systemTemp;
  final tempFilePath = '${tempDir.path}/$fileName';
  final tempFile = File(tempFilePath);
  await tempFile.writeAsBytes(bytes, flush: true);

  try {
    if (Platform.isAndroid) {
      await MediaStore.ensureInitialized();
      MediaStore.appFolder = 'TelurKu';
      final mediaStore = MediaStore();

      final saveInfo = await mediaStore.saveFile(
        tempFilePath: tempFilePath,
        dirType: DirType.download,
        dirName: DirName.download,
      );

      if (saveInfo != null) {
        return 'Download/TelurKu/${saveInfo.name}';
      }
    }
  } catch (_) {
    // Fallback to temp file when direct save is not available.
  }

  return tempFilePath;
}
