import 'package:dio/dio.dart';
import '../../../../core/config/api_endpoints.dart';
import '../models/chat_message_model.dart';

/// Remote datasource for chat operations against the IT0 backend API.
class ChatRemoteDatasource {
  final Dio _dio;

  ChatRemoteDatasource(this._dio);

  /// Creates a new agent task within a session.
  /// Returns the response data containing sessionId and taskId.
  Future<Map<String, dynamic>> createTask({
    required String sessionId,
    required String message,
    List<String>? attachments,
  }) async {
    final response = await _dio.post(
      ApiEndpoints.tasks,
      data: {
        'prompt': message,
        'sessionId': sessionId,
        if (attachments != null && attachments.isNotEmpty)
          'attachments': attachments,
      },
    );
    return response.data as Map<String, dynamic>;
  }

  /// Retrieves the message history for a given session.
  Future<List<ChatMessageModel>> getSessionHistory(String sessionId) async {
    final response = await _dio.get(
      '${ApiEndpoints.sessions}/$sessionId/messages',
    );

    final data = response.data;
    List<dynamic> messages;

    if (data is List) {
      messages = data;
    } else if (data is Map && data.containsKey('messages')) {
      messages = data['messages'] as List;
    } else if (data is Map && data.containsKey('items')) {
      messages = data['items'] as List;
    } else {
      messages = [];
    }

    return messages
        .map((m) => ChatMessageModel.fromJson(m as Map<String, dynamic>))
        .toList();
  }

  /// Approves a pending command for a given task.
  Future<void> approveCommand(String taskId) async {
    await _dio.post('${ApiEndpoints.approvals}/$taskId/approve');
  }

  /// Rejects a pending command for a given task with an optional reason.
  Future<void> rejectCommand(String taskId, {String? reason}) async {
    await _dio.post(
      '${ApiEndpoints.approvals}/$taskId/reject',
      data: {
        if (reason != null) 'reason': reason,
      },
    );
  }

  /// Cancels an active agent task in a session.
  Future<void> cancelTask(String sessionId) async {
    await _dio.post('${ApiEndpoints.sessions}/$sessionId/cancel');
  }

  /// Confirms a standing order draft proposed by the agent.
  Future<void> confirmStandingOrder(
    String sessionId,
    Map<String, dynamic> draft,
  ) async {
    await _dio.post(
      ApiEndpoints.standingOrders,
      data: {
        'sessionId': sessionId,
        ...draft,
      },
    );
  }
}
