import 'package:firebase_auth/firebase_auth.dart';
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].
  ///
  /// Requires a [ExampleConnector] from the data_connect package and [FirebaseAuth].
  const ProfileRepositoryImpl({
    required this.connector,
    required this.firebaseAuth,
  });

  /// The Data Connect connector used for data operations.
  final ExampleConnector connector;

  /// The Firebase Auth instance.
  final FirebaseAuth firebaseAuth;

  @override
  Future<Staff> getStaffProfile() async {
    final user = firebaseAuth.currentUser;
    if (user == null) {
      throw Exception('User not authenticated');
    }

    final response = await connector.getStaffByUserId(userId: user.uid).execute();
    
    if (response.data.staffs.isEmpty) {
      // TODO: Handle user not found properly with domain exception
      throw Exception('Staff not found');
    }

    final GetStaffByUserIdStaffs rawStaff = response.data.staffs.first;

    // 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 firebaseAuth.signOut();
    } catch (e) {
      throw Exception('Error signing out: ${e.toString()}');
    }
  }
}
