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

/// Remote datasource for task CRUD operations.
class TasksDatasource {
  final Dio _dio;

  TasksDatasource(this._dio);

  /// Fetches all tasks, optionally filtered by status.
  Future<List<TaskModel>> fetchTasks({String? status}) async {
    final queryParams = <String, dynamic>{};
    if (status != null) queryParams['status'] = status;

    final response = await _dio.get(
      ApiEndpoints.opsTasks,
      queryParameters: queryParams.isNotEmpty ? queryParams : null,
    );

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

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

    return items
        .map((item) => TaskModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  /// Fetches a single task by ID.
  Future<TaskModel> fetchTaskById(String id) async {
    final response = await _dio.get('${ApiEndpoints.opsTasks}/$id');
    return TaskModel.fromJson(response.data as Map<String, dynamic>);
  }

  /// Creates a new task.
  Future<TaskModel> createTask({
    required String title,
    String? description,
    String? priority,
    String? serverId,
  }) async {
    final body = <String, dynamic>{
      'title': title,
      if (description != null) 'description': description,
      if (priority != null) 'priority': priority,
      if (serverId != null) 'serverId': serverId,
    };

    final response = await _dio.post(ApiEndpoints.opsTasks, data: body);
    return TaskModel.fromJson(response.data as Map<String, dynamic>);
  }

  /// Updates an existing task.
  Future<TaskModel> updateTask(String id, Map<String, dynamic> updates) async {
    final response = await _dio.patch(
      '${ApiEndpoints.opsTasks}/$id',
      data: updates,
    );
    return TaskModel.fromJson(response.data as Map<String, dynamic>);
  }

  /// Deletes a task by ID.
  Future<void> deleteTask(String id) async {
    await _dio.delete('${ApiEndpoints.opsTasks}/$id');
  }
}
