import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:userfront/core/i18n/locale_registry.dart';
import 'package:userfront/core/i18n/locale_utils.dart';
import 'package:userfront/core/services/auth_token_store.dart';

class _AuthRefreshNotifier extends ChangeNotifier {
  void refresh() => notifyListeners();
}

Widget _buildRaceTestApp(_AuthRefreshNotifier notifier) {
  final router = GoRouter(
    initialLocation: '/ko/signin',
    refreshListenable: notifier,
    routes: [
      GoRoute(
        path: '/:locale',
        builder: (context, state) => const Scaffold(body: Text('locale-root')),
        routes: [
          GoRoute(
            path: 'dashboard',
            builder: (context, state) => const Scaffold(body: Text('home')),
          ),
          GoRoute(
            path: 'signin',
            builder: (context, state) {
              return Scaffold(
                body: Center(
                  child: FilledButton(
                    onPressed: () {
                      AuthTokenStore.setToken('race-token', provider: 'ory');
                      notifier.refresh();
                      context.go('/ko/dashboard');
                    },
                    child: const Text('login'),
                  ),
                ),
              );
            },
          ),
        ],
      ),
    ],
    redirect: (context, state) {
      final requestedLocale = extractLocaleFromPath(state.uri);
      if (requestedLocale == null) {
        return buildLocalizedPath(resolvePreferredLocaleCode(), state.uri);
      }

      final token = AuthTokenStore.getToken();
      final isLoggedIn =
          (token != null && token.isNotEmpty) || AuthTokenStore.usesCookie();
      final path = stripLocalePath(state.uri);
      if (path == '/signin') {
        return null;
      }
      if (!isLoggedIn) {
        return buildSigninRedirectPath(requestedLocale, state.uri);
      }
      if (path == '/') {
        return '/$requestedLocale/dashboard';
      }
      return null;
    },
  );

  return MaterialApp.router(routerConfig: router);
}

void main() {
  setUp(() {
    LocaleRegistry.setSupportedLocaleCodesForTest(['en', 'ko']);
    AuthTokenStore.clear();
  });

  tearDown(() {
    AuthTokenStore.clear();
    LocaleRegistry.resetForTest();
  });

  testWidgets('로그인 성공 이벤트(notify + go) 동시 호출 시 홈으로 안정적으로 이동', (tester) async {
    final notifier = _AuthRefreshNotifier();
    await tester.pumpWidget(_buildRaceTestApp(notifier));
    await tester.pumpAndSettle();
    expect(find.text('login'), findsOneWidget);

    await tester.tap(find.text('login'));
    await tester.pumpAndSettle();

    expect(find.text('home'), findsOneWidget);
    expect(tester.takeException(), isNull);
  });
}
