// Version: 1.0.0 | Created: 2026-04-01
// Riverpod controller for the login form.
// Owns the loading state visible to the login screen widget.

import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../../core/auth/auth_notifier.dart';
import '../../../core/auth/auth_state.dart';

part 'login_controller.g.dart';

@riverpod
class LoginController extends _$LoginController {
  @override
  bool build() => false; // isLoading

  /// Delegates to [AuthNotifier.login]. Returns the failure message if any,
  /// or null on success.
  Future<String?> login({
    required String username,
    required String password,
  }) async {
    state = true;
    try {
      await ref
          .read(authProvider.notifier)
          .login(username: username, password: password);

      // Check if auth failed.
      final authState = ref.read(authProvider);
      return authState.maybeWhen(
        unauthenticated: (failure) => failure,
        orElse: () => null,
      );
    } finally {
      state = false;
    }
  }
}
