import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/network/dio_client.dart';
import '../../data/datasources/tasks_datasource.dart';
import '../../data/repositories/tasks_repository_impl.dart';
import '../../domain/entities/task.dart';
import '../../domain/repositories/tasks_repository.dart';
import '../../domain/usecases/create_task.dart';
import '../../domain/usecases/get_tasks.dart';

// ---------------------------------------------------------------------------
// Dependency providers
// ---------------------------------------------------------------------------

final tasksDatasourceProvider = Provider<TasksDatasource>((ref) {
  final dio = ref.watch(dioClientProvider);
  return TasksDatasource(dio);
});

final tasksRepositoryProvider = Provider<TasksRepository>((ref) {
  final datasource = ref.watch(tasksDatasourceProvider);
  return TasksRepositoryImpl(datasource);
});

// ---------------------------------------------------------------------------
// Use case providers
// ---------------------------------------------------------------------------

final getTasksUseCaseProvider = Provider<GetTasks>((ref) {
  return GetTasks(ref.watch(tasksRepositoryProvider));
});

final createTaskUseCaseProvider = Provider<CreateTask>((ref) {
  return CreateTask(ref.watch(tasksRepositoryProvider));
});

// ---------------------------------------------------------------------------
// Data providers
// ---------------------------------------------------------------------------

/// Provides the full list of tasks.
final tasksListProvider = FutureProvider<List<Task>>((ref) async {
  final useCase = ref.watch(getTasksUseCaseProvider);
  return useCase.execute();
});

/// Provides tasks filtered by status.
final tasksByStatusProvider =
    FutureProvider.family<List<Task>, String>((ref, status) async {
  final useCase = ref.watch(getTasksUseCaseProvider);
  return useCase.execute(status: status);
});

/// Provides the list of available servers for the task creation form.
final serversForTaskPickerProvider =
    FutureProvider<List<Map<String, dynamic>>>((ref) async {
  final dio = ref.watch(dioClientProvider);
  final response = await dio.get('/api/v1/inventory/servers');
  final data = response.data;
  if (data is List) return data.cast<Map<String, dynamic>>();
  if (data is Map && data.containsKey('items')) {
    return (data['items'] as List).cast<Map<String, dynamic>>();
  }
  return [];
});
