import 'package:flutter_test/flutter_test.dart';
import 'package:userfront/core/services/oidc_redirect_guard.dart';

void main() {
  group('oidc_redirect_guard', () {
    test('http/https 절대 URL만 허용', () {
      final ok = validateOidcRedirectTarget(
        'https://sso-test.hmac.kr/oidc/oauth2/auth?client_id=devfront&login_verifier=abc&state=xyz&code_challenge=ccc&code_challenge_method=S256&response_type=code&scope=openid%20profile&redirect_uri=http%3A%2F%2Flocalhost%3A5174%2Fcallback',
      );
      expect(ok.isValid, isTrue);
      expect(ok.reason, 'ok');
      expect(ok.scheme, 'https');
      expect(ok.host, 'sso-test.hmac.kr');
      expect(ok.path, '/oidc/oauth2/auth');
      expect(ok.isOidcAuthPath, isTrue);
      expect(ok.queryParamCount, 8);
      expect(
        ok.queryKeys,
        containsAll(['client_id', 'login_verifier', 'state']),
      );
      expect(ok.hasLoginVerifier, isTrue);
      expect(ok.loginVerifierLength, 3);
      expect(ok.hasState, isTrue);
      expect(ok.stateLength, 3);
      expect(ok.hasClientId, isTrue);
      expect(ok.clientId, 'devfront');
      expect(ok.hasCodeChallenge, isTrue);
      expect(ok.codeChallengeLength, 3);
      expect(ok.codeChallengeMethod, 'S256');
      expect(ok.hasRedirectUri, isTrue);
      expect(ok.redirectUriScheme, 'http');
      expect(ok.redirectUriHost, 'localhost');
      expect(ok.redirectUriPort, 5174);
      expect(ok.redirectUriPath, '/callback');
      expect(ok.responseType, 'code');
      expect(ok.scopeCount, 2);
      expect(ok.toDiagnostics()['client_id'], 'devfront');

      final relative = validateOidcRedirectTarget('/oidc/oauth2/auth');
      expect(relative.isValid, isFalse);
      expect(relative.reason, 'not_absolute');

      final js = validateOidcRedirectTarget('javascript:alert(1)');
      expect(js.isValid, isFalse);
      expect(js.reason, 'not_absolute');
    });

    test('빈 문자열과 파싱 실패를 차단', () {
      final empty = validateOidcRedirectTarget('   ');
      expect(empty.isValid, isFalse);
      expect(empty.reason, 'empty');
      expect(empty.length, 0);
      expect(empty.queryParamCount, 0);
      expect(empty.hasRedirectUri, isFalse);

      final malformed = validateOidcRedirectTarget('https://[broken');
      expect(malformed.isValid, isFalse);
      expect(malformed.reason, 'parse_error');
      expect(malformed.queryParamCount, 0);
    });
  });
}
