import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/core/system/system_secure.dart';
import 'package:niogu_ecommerce_v1/core/system/system_setting.dart';
import 'package:niogu_ecommerce_v1/features/auth/data/models/auth_model.dart';
import 'package:niogu_ecommerce_v1/features/auth/domain/repositories/i_auth_repository.dart';
import 'package:niogu_ecommerce_v1/features/auth/presentation/providers/auth_provider.dart';

class AuthController extends AutoDisposeAsyncNotifier<void> {
  late final IAuthRepository _authRepository;

  @override
  FutureOr<void> build() {
    _authRepository = ref.read(authRepositoryProvider);
  }

  Future<void> login({
    required String identifier,
    required String password,
  }) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      final data = await _authRepository.login(
        identifier: identifier,
        password: password,
      );

      if (data == null) return;

      final accessToken = data.accessToken;

      final customer = data.customer;

      await SystemSecure.saveAccessToken(accessToken);

      await SystemSetting.setCustomerInfo(
        id: customer.uuid,
        name: customer.name,
        email: customer.email,
        phoneNumber: customer.phoneNumber,
      );

      await SystemSetting.setIsLoggedIn();
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> register(RegisterRequest request) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _authRepository.register(request);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }
}
