import '../../../core/i18n/locale_utils.dart';

const verificationRoutePath = '/verify';
const verificationCompletionRoutePath = '/verify-complete';
const verificationCompletionRouteName = 'verify-complete';

String buildLocalizedVerificationCompletePath(String localeCode) {
  return '/$localeCode$verificationCompletionRoutePath';
}

bool isDedicatedVerificationRoute(Uri uri) {
  final path = stripLocalePath(uri);
  return path == verificationRoutePath ||
      path == '/verification' ||
      path.startsWith('/verify/') ||
      path.startsWith('/l/');
}

bool hasVerificationPayload(Uri uri) {
  final query = uri.queryParameters;
  final token = query['t'];
  final loginId = query['loginId'];
  final code = query['code'];
  return (token != null && token.isNotEmpty) ||
      (loginId != null &&
          loginId.isNotEmpty &&
          code != null &&
          code.isNotEmpty);
}

String? buildDedicatedVerificationRedirect(
  Uri uri, {
  required String localeCode,
}) {
  if (isDedicatedVerificationRoute(uri)) {
    return null;
  }

  final query = uri.queryParameters;
  final token = query['t'];
  final loginId = query['loginId'];
  final code = query['code'];
  final pendingRef = query['pendingRef'];
  final sanitizedQuery = <String, String>{};

  if (token != null && token.isNotEmpty) {
    sanitizedQuery['t'] = token;
  } else if (loginId != null &&
      loginId.isNotEmpty &&
      code != null &&
      code.isNotEmpty) {
    sanitizedQuery['loginId'] = loginId;
    sanitizedQuery['code'] = code;
    if (pendingRef != null && pendingRef.isNotEmpty) {
      sanitizedQuery['pendingRef'] = pendingRef;
    }
  }

  if (sanitizedQuery.isEmpty) {
    return null;
  }

  return Uri(
    path: '/$localeCode$verificationRoutePath',
    queryParameters: sanitizedQuery,
  ).toString();
}
