import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/auth_state.dart';
import 'auth_service.dart';

final authControllerProvider = AsyncNotifierProvider<AuthController, AuthState>(
  AuthController.new,
);

class AuthController extends AsyncNotifier<AuthState> {
  @override
  Future<AuthState> build() async {
    final session = await ref.read(authServiceProvider).restoreSession();
    if (session == null) {
      return const AuthState.unauthenticated();
    }

    return AuthState.authenticated(
      token: session.token,
      userRole: session.userRole,
      routeId: session.routeId,
    );
  }

  Future<void> login({required String email, required String password}) async {
    state = const AsyncLoading<AuthState>();
    final session = await ref
        .read(authServiceProvider)
        .login(email: email, password: password);
    state = AsyncData(
      AuthState.authenticated(
        token: session.token,
        userRole: session.userRole,
        routeId: session.routeId,
      ),
    );
  }

  Future<void> register({
    required String email,
    required String phone,
    required String password,
  }) async {
    state = const AsyncLoading<AuthState>();
    final session = await ref
        .read(authServiceProvider)
        .register(email: email, phone: phone, password: password);
    state = AsyncData(
      AuthState.authenticated(
        token: session.token,
        userRole: session.userRole,
        routeId: session.routeId,
      ),
    );
  }

  Future<void> logout() async {
    await ref.read(authServiceProvider).logout();
    state = const AsyncData(AuthState.unauthenticated());
  }
}
