/// Customer Groups Provider
///
/// Manages the list of customer groups (roles) for user registration
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/customer_group.dart';
import 'package:worker/features/auth/presentation/providers/session_provider.dart';

part 'customer_groups_provider.g.dart';

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

  /// Fetch customer groups from API
  Future<void> fetchCustomerGroups() 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.getCustomerGroups(
        csrfToken: sessionState.csrfToken!,
        sid: sessionState.sid!,
      );
    });
  }

  /// Refresh customer groups list
  Future<void> refresh() async {
    await fetchCustomerGroups();
  }
}

/// Provider to get a specific customer group by code/value
@riverpod
CustomerGroup? customerGroupByCode(
  Ref ref,
  String code,
) {
  final groupsAsync = ref.watch(customerGroupsProvider);

  return groupsAsync.whenOrNull(
    data: (List<CustomerGroup> groups) => groups.firstWhere(
      (CustomerGroup group) => group.value == code || group.name == code,
      orElse: () => groups.first,
    ),
  );
}
