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/directory/data/directory_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('lists employees with bearer token and query filters', () async {
    final client = DirectoryApiClient(
      httpClient: MockClient((request) async {
        expect(request.headers['authorization'], 'Bearer session-token');
        expect(request.url.path, '/api/v1/tdc114plus/directory/employees');
        expect(request.url.queryParameters['q'], 'kim');
        expect(request.url.queryParameters['tenantSlug'], 'hanmac');
        return http.Response(
          jsonEncode({
            'items': [
              {
                'id': 'user-uuid',
                'name': 'User One',
                'phoneNumber': '+821012345678',
                'phoneDisplay': '010-1234-5678',
                'tenantId': 'tenant-uuid',
                'tenantName': 'Hanmac',
                'tenantSlug': 'hanmac',
                'status': 'active',
              },
            ],
            'limit': 50,
            'offset': 0,
            'total': 1,
            'nextCursor': '',
          }),
          200,
        );
      }),
      baseUri: Uri.parse('https://sso.example.test'),
      sessionStore: const AuthSessionStore(),
    );

    final response = await client.listEmployees(
      query: 'kim',
      tenantSlug: 'hanmac',
    );

    expect(response.total, 1);
    expect(response.items.single.phoneDisplay, '010-1234-5678');
  });
}
