import 'package:flutter_test/flutter_test.dart';
import 'package:userfront/features/dashboard/domain/linked_rp_launch.dart';
import 'package:userfront/features/dashboard/domain/models.dart';

LinkedRp _linkedRp({
  required String status,
  String url = '',
  String initUrl = '',
  bool autoLoginSupported = false,
  String autoLoginUrl = '',
}) {
  return LinkedRp(
    id: 'client-1',
    name: 'Example App',
    logo: '',
    url: url,
    initUrl: initUrl,
    autoLoginSupported: autoLoginSupported,
    autoLoginUrl: autoLoginUrl,
    status: status,
    scopes: const ['openid', 'profile'],
    lastAuthenticatedAt: null,
  );
}

void main() {
  test('LinkedRp.fromJson은 init_url을 읽는다', () {
    final rp = LinkedRp.fromJson({
      'id': 'client-1',
      'name': 'Example App',
      'status': 'active',
      'url': 'https://example.com',
      'init_url': 'https://sso.example.com/oidc/oauth2/auth?client_id=client-1',
      'auto_login_supported': true,
      'auto_login_url': 'https://example.com/login?auto=1',
    });

    expect(
      rp.initUrl,
      'https://sso.example.com/oidc/oauth2/auth?client_id=client-1',
    );
    expect(rp.autoLoginSupported, isTrue);
    expect(rp.autoLoginUrl, 'https://example.com/login?auto=1');
  });

  test('자동 로그인 지원 앱은 autoLoginUrl을 우선 진입 URL로 사용한다', () {
    final launchUrl = resolveLinkedRpLaunchUrl(
      _linkedRp(
        status: 'active',
        url: 'https://example.com',
        initUrl: 'https://sso.example.com/oidc/oauth2/auth?client_id=client-1',
        autoLoginSupported: true,
        autoLoginUrl: 'https://example.com/login?auto=1',
      ),
    );

    expect(launchUrl, 'https://example.com/login?auto=1');
  });

  test('자동 로그인 지원 앱은 autoLoginUrl이 없으면 initUrl로 폴백한다', () {
    final launchUrl = resolveLinkedRpLaunchUrl(
      _linkedRp(
        status: 'active',
        url: 'https://example.com',
        initUrl: 'https://example.com/login?auto=1',
        autoLoginSupported: true,
      ),
    );

    expect(launchUrl, 'https://example.com/login?auto=1');
  });

  test('자동 로그인 미지원 앱은 initUrl이 있어도 기존 url로 폴백한다', () {
    final launchUrl = resolveLinkedRpLaunchUrl(
      _linkedRp(
        status: 'active',
        url: 'https://example.com',
        initUrl: 'https://sso.example.com/oidc/oauth2/auth?client_id=client-1',
        autoLoginSupported: false,
      ),
    );

    expect(launchUrl, 'https://example.com');
  });

  test('활성 앱은 자동 로그인 URL이 없으면 기존 url로 폴백한다', () {
    final launchUrl = resolveLinkedRpLaunchUrl(
      _linkedRp(status: 'active', url: 'https://example.com'),
    );

    expect(launchUrl, 'https://example.com');
  });

  test('비활성 앱은 진입 URL을 만들지 않는다', () {
    final launchUrl = resolveLinkedRpLaunchUrl(
      _linkedRp(
        status: 'inactive',
        url: 'https://example.com',
        initUrl: 'https://sso.example.com/oidc/oauth2/auth?client_id=client-1',
      ),
    );

    expect(launchUrl, isNull);
  });
}
