import 'package:firebase_auth/firebase_auth.dart';
import 'package:krow_data_connect/krow_data_connect.dart' as dc;
import 'package:krow_domain/krow_domain.dart';
import '../../domain/repositories/emergency_contact_repository_interface.dart';

/// Implementation of [EmergencyContactRepositoryInterface].
///
/// This repository delegates data operations to Firebase Data Connect.
class EmergencyContactRepositoryImpl
    implements EmergencyContactRepositoryInterface {
  final dc.ExampleConnector _dataConnect;
  final FirebaseAuth _firebaseAuth;

  /// Creates an [EmergencyContactRepositoryImpl].
  EmergencyContactRepositoryImpl({
    required dc.ExampleConnector dataConnect,
    required FirebaseAuth firebaseAuth,
  })  : _dataConnect = dataConnect,
        _firebaseAuth = firebaseAuth;

  Future<String> _getStaffId() async {
    final user = _firebaseAuth.currentUser;
    if (user == null) throw Exception('User not authenticated');

    final result =
        await _dataConnect.getStaffByUserId(userId: user.uid).execute();
    if (result.data.staffs.isEmpty) {
      throw Exception('Staff profile not found');
    }
    return result.data.staffs.first.id;
  }

  @override
  Future<List<EmergencyContact>> getContacts() async {
    final staffId = await _getStaffId();
    final result =
        await _dataConnect.getEmergencyContactsByStaffId(staffId: staffId).execute();

    return result.data.emergencyContacts.map((dto) {
      return EmergencyContactAdapter.fromPrimitives(
        id: dto.id,
        name: dto.name,
        phone: dto.phone,
        relationship: dto.relationship.stringValue,
      );
    }).toList();
  }

  @override
  Future<void> saveContacts(List<EmergencyContact> contacts) async {
    final staffId = await _getStaffId();

    // 1. Get existing to delete
    final existingResult =
        await _dataConnect.getEmergencyContactsByStaffId(staffId: staffId).execute();
    final existingIds =
        existingResult.data.emergencyContacts.map((e) => e.id).toList();

    // 2. Delete all existing
    await Future.wait(existingIds.map(
        (id) => _dataConnect.deleteEmergencyContact(id: id).execute()));

    // 3. Create new
    await Future.wait(contacts.map((contact) {
      dc.RelationshipType rel = dc.RelationshipType.OTHER;
      switch(contact.relationship) {
          case RelationshipType.family: rel = dc.RelationshipType.FAMILY; break;
          case RelationshipType.spouse: rel = dc.RelationshipType.SPOUSE; break;
          case RelationshipType.friend: rel = dc.RelationshipType.FRIEND; break;
          case RelationshipType.other: rel = dc.RelationshipType.OTHER; break;
      }

      return _dataConnect
          .createEmergencyContact(
            name: contact.name,
            phone: contact.phone,
            relationship: rel,
            staffId: staffId,
          )
          .execute();
    }));
  }
}