// lib/services/submission_ftp_service.dart

import 'dart:io';
import 'package:flutter/foundation.dart';

import 'package:environment_monitoring_app/services/user_preferences_service.dart';
import 'package:environment_monitoring_app/services/ftp_service.dart';
import 'package:environment_monitoring_app/services/retry_service.dart';

/// A generic, reusable service for handling the FTP submission process.
/// It respects user preferences for enabled destinations for any given module.
class SubmissionFtpService {
  final UserPreferencesService _userPreferencesService = UserPreferencesService();
  final FtpService _ftpService = FtpService();
  final RetryService _retryService = RetryService();

  /// Submits a file to all enabled FTP destinations for a given module.
  ///
  /// This method works differently from the API service. It attempts to upload
  /// to ALL enabled destinations. It returns a summary of success/failure for each.
  /// If any upload fails, it is queued for individual retry.
  /// The overall result is considered successful if there are no hard errors
  /// during the process, even if some uploads are queued.
  Future<Map<String, dynamic>> submit({
    required String moduleName,
    required File fileToUpload,
    required String remotePath,
  }) async {
    final destinations = await _userPreferencesService.getEnabledFtpConfigsForModule(moduleName);

    if (destinations.isEmpty) {
      debugPrint("SubmissionFtpService: No enabled FTP destinations for module '$moduleName'. Skipping.");
      return {'success': true, 'message': 'No FTP destinations enabled for this module.'};
    }

    final List<Map<String, dynamic>> statuses = [];
    bool allSucceeded = true;

    for (final dest in destinations) {
      final configName = dest['config_name'] as String? ?? 'Unknown FTP';
      debugPrint("SubmissionFtpService: Attempting to upload to '$configName'");

      final result = await _ftpService.uploadFile(
        config: dest,
        fileToUpload: fileToUpload,
        remotePath: remotePath,
      );

      statuses.add({
        'config_name': configName,
        'success': result['success'],
        'message': result['message'],
      });

      if (result['success'] != true) {
        allSucceeded = false;
        // If an individual upload fails, queue it for manual retry.
        debugPrint("SubmissionFtpService: Upload to '$configName' failed. Queuing for retry.");
        await _retryService.addFtpToQueue(
          localFilePath: fileToUpload.path,
          remotePath: remotePath,
        );
      }
    }

    if (allSucceeded) {
      return {
        'success': true,
        'message': 'File successfully uploaded to all enabled FTP destinations.',
        'statuses': statuses,
      };
    } else {
      return {
        'success': true, // The process itself succeeded, even if some uploads were queued.
        'message': 'One or more FTP uploads failed and have been queued for retry.',
        'statuses': statuses,
      };
    }
  }
}