import '../features/directory/data/directory_repository.dart';
import '../features/directory/data/mock_directory_data.dart';
import '../features/directory/domain/employee.dart';
import '../features/organization/data/organization_api_client.dart';
import '../features/organization/domain/organization_models.dart';

const useSmokeMockDirectory = bool.fromEnvironment(
  'TDC114_SMOKE_USE_MOCK_DIRECTORY',
);

final smokeDirectoryOverride = directoryRepositoryProvider.overrideWithValue(
  const _SmokeDirectoryRepository(),
);

final smokeOrganizationOverride = organizationRepositoryProvider
    .overrideWithValue(const _SmokeOrganizationRepository());

class _SmokeDirectoryRepository implements DirectoryRepository {
  const _SmokeDirectoryRepository();

  @override
  Future<List<Employee>> loadEmployees(DirectoryQuery query) async {
    final normalizedQuery = query.query.trim();
    final normalizedDigits = _digitsOnly(normalizedQuery);
    final selectedTenant = _findTenantBySlug(query.apiTenantSlug);

    return mockEmployees.where((employee) {
      final matchesTenant =
          query.apiTenantSlug == null ||
          employee.tenantSlug == query.apiTenantSlug ||
          (selectedTenant != null &&
              selectedTenant.type != 'COMPANY' &&
              (employee.department ?? '') == selectedTenant.name);
      final matchesDepartment =
          query.apiDepartment == null ||
          (employee.department ?? '') == query.apiDepartment;
      if (!matchesTenant) {
        return false;
      }
      if (!matchesDepartment) {
        return false;
      }

      if (normalizedQuery.isEmpty) {
        return true;
      }

      final matchesName = employee.name.contains(normalizedQuery);
      final matchesDepartmentQuery = (employee.department ?? '').contains(
        normalizedQuery,
      );
      final matchesPhone =
          normalizedDigits.isNotEmpty &&
          (_digitsOnly(employee.phoneNumber).contains(normalizedDigits) ||
              _digitsOnly(
                employee.phoneDisplay ?? '',
              ).contains(normalizedDigits));
      return matchesName || matchesDepartmentQuery || matchesPhone;
    }).toList();
  }

  String _digitsOnly(String value) => value.replaceAll(RegExp(r'[^0-9]'), '');

  TenantSummary? _findTenantBySlug(String? slug) {
    if (slug == null || slug.trim().isEmpty) {
      return null;
    }
    for (final tenant in mockTenants) {
      if (tenant.slug == slug) {
        return tenant;
      }
    }
    return null;
  }
}

class _SmokeOrganizationRepository implements OrganizationRepository {
  const _SmokeOrganizationRepository();

  @override
  Future<OrgChartSnapshot> getOrgChart({
    String? tenantId,
    bool refresh = false,
  }) {
    throw UnimplementedError();
  }

  @override
  Future<TenantListResponse> listTenants() async {
    return TenantListResponse(
      items: mockTenants,
      generatedAt: DateTime.parse('2026-07-02T00:00:00Z'),
    );
  }
}
