import 'dart:convert';

import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tdc114plus/src/features/auth/data/auth_session_store.dart';
import 'package:tdc114plus/src/features/auth/domain/auth_models.dart';
import 'package:tdc114plus/src/features/organization/data/organization_api_client.dart';

void main() {
  setUp(() async {
    SharedPreferences.setMockInitialValues({});
    await const AuthSessionStore().save(
      PhoneLoginResponse(
        status: 'ok',
        token: 'session-token',
        expiresAt: DateTime.parse('2026-07-02T12:00:00Z'),
        user: const LoginUser(
          id: 'user-uuid',
          name: 'User One',
          phoneNumber: '+821012345678',
          tenantId: 'tenant-uuid',
          tenantName: 'Hanmac',
          tenantSlug: 'hanmac',
        ),
      ),
    );
  });

  test('loads org chart with bearer token', () async {
    final client = OrganizationApiClient(
      httpClient: MockClient((request) async {
        expect(request.headers['authorization'], 'Bearer session-token');
        expect(request.url.path, '/api/v1/tdc114plus/organization/orgchart');
        return http.Response(
          jsonEncode({
            'tenants': [
              {
                'id': 'tenant-uuid',
                'name': 'Hanmac',
                'slug': 'hanmac',
                'type': 'COMPANY',
                'memberCount': 1,
                'totalMemberCount': 1,
              },
            ],
            'employees': [
              {
                'id': 'user-uuid',
                'name': 'User One',
                'phoneNumber': '+821012345678',
                'tenantId': 'tenant-uuid',
                'tenantName': 'Hanmac',
                'tenantSlug': 'hanmac',
              },
            ],
            'generatedAt': '2026-07-02T12:00:00Z',
            'cache': {'source': 'db', 'hit': false, 'ttlSeconds': 0},
          }),
          200,
        );
      }),
      baseUri: Uri.parse('https://sso.example.test'),
      sessionStore: const AuthSessionStore(),
    );

    final snapshot = await client.getOrgChart();

    expect(snapshot.tenants.single.slug, 'hanmac');
    expect(snapshot.employees.single.name, 'User One');
  });
}
