import 'package:dio/dio.dart';
import 'package:niogu_app/core/constants/app_generator.dart';
import 'package:niogu_app/core/errors/exceptions.dart';
import 'package:niogu_app/core/models/api_response.dart';
import 'package:niogu_app/features/auth/data/datasource/auth_remote_datasource_impl.dart';
import 'package:niogu_app/features/auth/data/models/login_response_model.dart';
import 'package:niogu_app/features/auth/data/models/register_request_model.dart';
import 'package:niogu_app/features/auth/domain/entities/user.dart';
import 'package:niogu_app/features/auth/domain/repositories/i_auth_repository.dart';

class AuthRepositoryImpl implements IAuthRepository {
  final IAuthRemoteDatasource _datasource;

  AuthRepositoryImpl(this._datasource);

  @override
  Future<ApiResponseModel<LoginResponseModel>> login(LoginUser user) async {
    try {
      return await _datasource.login(
        identifier: user.identifier,
        password: user.password,
        businessCode: user.businessCode,
      );
    } on DioException catch (e) {
      String errorMessage = "Terjadi kesalahan koneksi";

      final statusCode = e.response?.statusCode;

      final data = e.response?.data;

      if (statusCode != null && data != null) {
        final error = data['error'];

        if (statusCode == 401) {
          errorMessage = "Akun tidak ditemukan";
        }

        if (statusCode == 429 && error != null && error is Map) {
          final seconds = error['seconds_remaining'];
          if (seconds != null) {
            final minutes = (seconds / 60).ceil();
            errorMessage =
                "Terlalu banyak percobaan. Coba lagi dalam $minutes menit.";
          }
        }
      }

      throw ServerException(errorMessage);
    }
  }

  @override
  Future<void> register(RegisterUser register) async {
    try {
      await _datasource.register(
        RegisterRequestModel(
          businessName: register.businessName,
          businessCode: AppGenerator.generateBusinessCode(),
          name: register.ownerName,
          phoneNumber: register.phoneNumber,
          email: register.email,
          password: register.password,
          passwordConfirmation: register.passwordConfirmation,
        ),
      );
    } on DioException catch (e) {
      String errorMessage = "Terjadi kesalahan koneksi";

      if (e.response != null) {
        final data = e.response!.data;

        final statusCode = e.response!.statusCode;

        if (statusCode == 422) {
          if (data['errors'] != null && data['errors'] is Map) {
            final Map<String, dynamic> validationErrors = data['errors'];

            final firstKey = validationErrors.keys.first;

            final List<dynamic> messages = validationErrors[firstKey];

            final message = messages.first.toString();

            if (message == 'phone number already exists') {
              errorMessage = "Nomor whatsapp telah terdaftar";
            } else if (message == 'email already exists') {
              errorMessage = "Email telah terdaftar";
            }
          }
        }
      }
      throw ServerException(errorMessage);
    }
  }
}
