/// Cities Provider
///
/// Manages the list of cities/provinces for address selection
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/features/auth/data/datasources/auth_remote_datasource.dart';
import 'package:worker/features/auth/domain/entities/city.dart';
import 'package:worker/features/auth/presentation/providers/session_provider.dart';

part 'cities_provider.g.dart';

/// Cities Provider
///
/// Fetches list of cities from API for registration form.
/// Requires active session (CSRF token and SID).
/// keepAlive: true ensures the cities list persists and doesn't auto-dispose.
@Riverpod(keepAlive: true)
class Cities extends _$Cities {
  @override
  Future<List<City>> build() async {
    // Don't auto-fetch on build, wait for manual call
    return [];
  }

  /// Fetch cities from API
  Future<void> fetchCities() async {
    state = const AsyncValue.loading();

    state = await AsyncValue.guard(() async {
      final sessionState = ref.read(sessionProvider);

      if (!sessionState.hasSession) {
        throw Exception('No active session. Please get session first.');
      }

      final dataSource = ref.read(authRemoteDataSourceProvider);
      return await dataSource.getCities(
        csrfToken: sessionState.csrfToken!,
        sid: sessionState.sid!,
      );
    });
  }

  /// Refresh cities list
  Future<void> refresh() async {
    await fetchCities();
  }
}

/// Provider to get a specific city by code
@riverpod
City? cityByCode(Ref ref, String code) {
  final citiesAsync = ref.watch(citiesProvider);

  return citiesAsync.whenOrNull(
    data: (List<City> cities) => cities.firstWhere(
      (City city) => city.code == code,
      orElse: () => cities.first,
    ),
  );
}
