/// Design Request Remote Data Source
///
/// Handles remote API calls for design requests.
library;

import 'package:dio/dio.dart';
import 'package:worker/core/constants/api_constants.dart';
import 'package:worker/core/network/dio_client.dart';
import 'package:worker/features/showrooms/data/models/design_request_model.dart';

/// Design Request Remote Data Source Interface
abstract class DesignRequestRemoteDataSource {
  /// Fetch list of design requests from API
  Future<List<DesignRequestModel>> getDesignRequests({
    int limitStart = 0,
    int limitPageLength = 0,
  });

  /// Fetch detail of a design request by name
  Future<DesignRequestModel> getDesignRequestDetail(String name);

  /// Create a new design request
  Future<String> createDesignRequest({
    required String subject,
    required String area,
    required String region,
    required String desiredStyle,
    String? estimatedBudget,
    required String detailedRequirements,
    required String dateline,
  });

  /// Upload file attachment for a design request
  Future<void> uploadDesignRequestFile({
    required String requestId,
    required String filePath,
    required String fileName,
  });
}

/// Design Request Remote Data Source Implementation
class DesignRequestRemoteDataSourceImpl implements DesignRequestRemoteDataSource {
  const DesignRequestRemoteDataSourceImpl(this._dioClient);

  final DioClient _dioClient;

  /// Get list of design requests
  ///
  /// Calls: POST /api/method/building_material.building_material.api.design_request.get_list
  /// Body: { "limit_start": 0, "limit_page_length": 0 }
  /// Returns: List of design requests
  @override
  Future<List<DesignRequestModel>> getDesignRequests({
    int limitStart = 0,
    int limitPageLength = 0,
  }) async {
    try {
      final response = await _dioClient.post<Map<String, dynamic>>(
        '${ApiConstants.frappeApiMethod}${ApiConstants.getDesignRequestList}',
        data: {
          'limit_start': limitStart,
          'limit_page_length': limitPageLength,
        },
      );

      final data = response.data;
      if (data == null) {
        throw Exception('No data received from getDesignRequestList API');
      }

      // API returns: { "message": [...] }
      final message = data['message'];
      if (message == null) {
        throw Exception('No message field in getDesignRequestList response');
      }

      final List<dynamic> requestsList = message as List<dynamic>;
      return requestsList
          .map((json) => DesignRequestModel.fromJson(json as Map<String, dynamic>))
          .toList();
    } catch (e) {
      throw Exception('Failed to get design requests: $e');
    }
  }

  /// Get detail of a design request by name
  ///
  /// Calls: POST /api/method/building_material.building_material.api.design_request.get_detail
  /// Body: { "name": "ISS-2025-00005" }
  /// Returns: Full design request detail with files_list
  @override
  Future<DesignRequestModel> getDesignRequestDetail(String name) async {
    try {
      final response = await _dioClient.post<Map<String, dynamic>>(
        '${ApiConstants.frappeApiMethod}${ApiConstants.getDesignRequestDetail}',
        data: {'name': name},
      );

      final data = response.data;
      if (data == null) {
        throw Exception('No data received from getDesignRequestDetail API');
      }

      // API returns: { "message": {...} }
      final message = data['message'];
      if (message == null) {
        throw Exception('No message field in getDesignRequestDetail response');
      }

      return DesignRequestModel.fromJson(message as Map<String, dynamic>);
    } catch (e) {
      throw Exception('Failed to get design request detail: $e');
    }
  }

  /// Create a new design request
  ///
  /// Calls: POST /api/method/building_material.building_material.api.design_request.create
  /// Body: { "subject": "...", "area": "...", "region": "...", ... }
  /// Returns: Created request ID (name)
  @override
  Future<String> createDesignRequest({
    required String subject,
    required String area,
    required String region,
    required String desiredStyle,
    String? estimatedBudget,
    required String detailedRequirements,
    required String dateline,
  }) async {
    try {
      final response = await _dioClient.post<Map<String, dynamic>>(
        '${ApiConstants.frappeApiMethod}${ApiConstants.createDesignRequest}',
        data: {
          'subject': subject,
          'area': area,
          'region': region,
          'desired_style': desiredStyle,
          if (estimatedBudget != null) 'estimated_budget': estimatedBudget,
          'detailed_requirements': detailedRequirements,
          'dateline': dateline,
        },
      );

      final data = response.data;
      if (data == null) {
        throw Exception('No data received from createDesignRequest API');
      }

      // API returns: { "message": { "success": true, "data": { "name": "ISS-2025-00006" } } }
      final message = data['message'] as Map<String, dynamic>?;
      if (message == null) {
        throw Exception('No message field in createDesignRequest response');
      }

      final success = message['success'] as bool? ?? false;
      if (!success) {
        throw Exception('Failed to create design request');
      }

      final requestData = message['data'] as Map<String, dynamic>?;
      if (requestData == null) {
        throw Exception('No data field in createDesignRequest response');
      }

      final name = requestData['name'] as String?;
      if (name == null || name.isEmpty) {
        throw Exception('No name returned from createDesignRequest');
      }

      return name;
    } catch (e) {
      throw Exception('Failed to create design request: $e');
    }
  }

  /// Upload file attachment for a design request
  ///
  /// Calls: POST /api/method/upload_file
  /// Form-data: { file, is_private, folder, doctype, docname, optimize }
  @override
  Future<void> uploadDesignRequestFile({
    required String requestId,
    required String filePath,
    required String fileName,
  }) async {
    try {
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(filePath, filename: fileName),
        'is_private': '0',
        'folder': 'Home/Attachments',
        'doctype': 'Issue',
        'docname': requestId,
        'optimize': 'true',
      });

      await _dioClient.post<Map<String, dynamic>>(
        '${ApiConstants.frappeApiMethod}${ApiConstants.uploadFile}',
        data: formData,
      );
    } catch (e) {
      throw Exception('Failed to upload file: $e');
    }
  }
}
