// lib/services/ftp_service.dart

import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:ftpconnect/ftpconnect.dart';
import 'package:environment_monitoring_app/services/retry_service.dart';

/// A low-level service for making a direct FTP connection and uploading a single file.
/// This service only performs the upload; it does not decide which server to use.
class FtpService {
  /// Uploads a single file to a specific FTP server defined in the config.
  ///
  /// [config] A map containing FTP credentials ('ftp_host', 'ftp_user', 'ftp_pass', 'ftp_port').
  /// [fileToUpload] The local file to be uploaded.
  /// [remotePath] The destination path on the FTP server.
  /// Returns a map with 'success' and 'message' keys.
  Future<Map<String, dynamic>> uploadFile({
    required Map<String, dynamic> config,
    required File fileToUpload,
    required String remotePath,
  }) async {
    final ftpHost = config['ftp_host'] as String?;
    final ftpUser = config['ftp_user'] as String?;
    final ftpPass = config['ftp_pass'] as String?;
    final ftpPort = config['ftp_port'] as int? ?? 21;

    if (ftpHost == null || ftpUser == null || ftpPass == null) {
      final message = 'FTP configuration is incomplete. Missing host, user, or password.';
      debugPrint('FTP: $message');
      return {'success': false, 'message': message};
    }

    final ftpConnect = FTPConnect(
      ftpHost,
      user: ftpUser,
      pass: ftpPass,
      port: ftpPort,
      showLog: kDebugMode,
      timeout: 60,
    );

    try {
      debugPrint('FTP: Connecting to $ftpHost...');
      await ftpConnect.connect();

      debugPrint('FTP: Uploading file ${fileToUpload.path} to $remotePath...');
      bool res = await ftpConnect.uploadFileWithRetry(
        fileToUpload,
        pRemoteName: remotePath,
        pRetryCount: 3,
      );

      await ftpConnect.disconnect();
      if (res) {
        debugPrint('FTP upload to $ftpHost succeeded.');
        return {'success': true, 'message': 'File uploaded successfully to $ftpHost.'};
      } else {
        debugPrint('FTP upload to $ftpHost failed after retries.');
        return {'success': false, 'message': 'FTP upload to $ftpHost failed after retries.'};
      }
    } catch (e) {
      debugPrint('FTP upload to $ftpHost failed with an exception. Error: $e');
      try {
        await ftpConnect.disconnect();
      } catch (_) {}
      return {'success': false, 'message': 'FTP upload to $ftpHost failed: $e'};
    }
  }
}