import 'package:file_picker/file_picker.dart';

class FileUploadService {
  FileUploadService._();
  static final FileUploadService _instance = FileUploadService._();
  factory FileUploadService() => _instance;

  PlatformFile? singleFile;

  /// Default allowed extensions
  static const defaultAllowedExtensions = ['pdf', 'png', 'jpg', 'jpeg'];
  // static const allowedExtensions = ['pdf', 'png', 'jpg', 'jpeg'];

  Future<String?> pickSingleFile({
    int maxFileSizeInMB = 5,
    List<String>? allowedExtensions,
  }) async {
    final extensions = allowedExtensions ?? defaultAllowedExtensions;
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: false,
      withData: true,
      type: FileType.custom,
      allowedExtensions: extensions,
    );

    if (result != null && result.files.isNotEmpty) {
      final file = result.files.first;
      final ext = file.extension?.toLowerCase() ?? '';
      // final sizeInMB = file.size / (1024 * 1024);

      if (!extensions.contains(ext)) {
        return "Unsupported format: ${file.name}";
      }
      // if (sizeInMB > maxFileSizeInMB) {
      //   return "File too large (${file.name}). Max $maxFileSizeInMB MB allowed.";
      // }

      singleFile = file;
    }
    return null; // success
  }

  void clearSingle() {
    singleFile = null;
  }
}
