import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:krow_domain/krow_domain.dart';

import '../../domain/repositories/profile_repository.dart';

/// Implementation of [ProfileRepositoryInterface] that delegates to data_connect.
///
/// This implementation follows Clean Architecture by:
/// - Implementing the domain layer's repository interface
/// - Delegating all data access to the data_connect package
/// - Not containing any business logic
/// - Only performing data transformation/mapping if needed
///
/// Currently uses [ProfileRepositoryMock] from data_connect.
/// When Firebase Data Connect is ready, this will be swapped with a real implementation.
class ProfileRepositoryImpl
    implements ProfileRepositoryInterface {
  /// Creates a [ProfileRepositoryImpl].
  ProfileRepositoryImpl() : _service = DataConnectService.instance;

  final DataConnectService _service;

  @override
  Future<Staff> getStaffProfile() async {
    return _service.run(() async {
      final staffId = await _service.getStaffId();
      final response = await _service.connector.getStaffById(id: staffId).execute();
      
      if (response.data.staff == null) {
        throw const ServerException(technicalMessage: 'Staff not found');
      }

      final GetStaffByIdStaff rawStaff = response.data.staff!;

      // Map the raw data connect object to the Domain Entity
      return Staff(
        id: rawStaff.id,
        authProviderId: rawStaff.userId,
        name: rawStaff.fullName,
        email: rawStaff.email ?? '',
        phone: rawStaff.phone,
        avatar: rawStaff.photoUrl,
        status: StaffStatus.active,
        address: rawStaff.addres,
        totalShifts: rawStaff.totalShifts,
        averageRating: rawStaff.averageRating,
        onTimeRate: rawStaff.onTimeRate,
        noShowCount: rawStaff.noShowCount,
        cancellationCount: rawStaff.cancellationCount,
        reliabilityScore: rawStaff.reliabilityScore,
      );
    });
  }

  @override
  Future<void> signOut() async {
    try {
      await _service.auth.signOut();
      _service.clearCache();
    } catch (e) {
      throw Exception('Error signing out: ${e.toString()}');
    }
  }
}
