import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:firebase_data_connect/firebase_data_connect.dart' as fdc;
import 'package:krow_domain/krow_domain.dart';
import 'package:firebase_auth/firebase_auth.dart' as auth;
import '../../domain/repositories/profile_setup_repository.dart';

class ProfileSetupRepositoryImpl implements ProfileSetupRepository {
  final DataConnectService _service;

  ProfileSetupRepositoryImpl() : _service = DataConnectService.instance;

  @override
  Future<void> submitProfile({
    required String fullName,
    String? bio,
    required List<String> preferredLocations,
    required double maxDistanceMiles,
    required List<String> industries,
    required List<String> skills,
  }) async {
    return _service.run(() async {
      final auth.User? firebaseUser = _service.auth.currentUser;
      if (firebaseUser == null) {
        throw const NotAuthenticatedException(
            technicalMessage: 'User not authenticated.');
      }

      final StaffSession? session = StaffSessionStore.instance.session;
      final String email = session?.user.email ?? '';
      final String? phone = firebaseUser.phoneNumber;

      final fdc.OperationResult<CreateStaffData, CreateStaffVariables> result =
          await _service.connector
              .createStaff(
                userId: firebaseUser.uid,
                fullName: fullName,
              )
              .bio(bio)
              .preferredLocations(preferredLocations)
              .maxDistanceMiles(maxDistanceMiles.toInt())
              .industries(industries)
              .skills(skills)
              .email(email.isEmpty ? null : email)
              .phone(phone)
              .execute();

      final String staffId = result.data.staff_insert.id;
      
      final Staff staff = Staff(
        id: staffId,
        authProviderId: firebaseUser.uid,
        name: fullName,
        email: email,
        phone: phone,
        status: StaffStatus.completedProfile,
      );
      
      if (session != null) {
        StaffSessionStore.instance.setSession(
          StaffSession(user: session.user, staff: staff, ownerId: session.ownerId),
        );
      }
    });
  }
}
