import 'package:pshared/data/mapper/invitation/invitation.dart';
import 'package:pshared/models/invitation/invitation.dart';
import 'package:pshared/models/invitation/status.dart';
import 'package:pshared/provider/organizations.dart';
import 'package:pshared/provider/template.dart';
import 'package:pshared/service/invitation/service.dart';


class InvitationsProvider extends GenericProvider<Invitation> {
  InvitationsProvider() : super(service: InvitationService.basicService);

  late OrganizationsProvider _organizations;
  String? _loadedOrganizationId;

  List<Invitation> get invitations => List<Invitation>.unmodifiable(items);

  void updateProviders(OrganizationsProvider organizations) {
    _organizations = organizations;
    if (_organizations.isOrganizationSet) {
      final organizationId = _organizations.current.id;
      if (_loadedOrganizationId != organizationId) {
        _loadedOrganizationId = organizationId;
        load(organizationId, organizationId);
      }
    }
  }

  Future<Invitation> sendInvitation({
    required String email,
    required String roleRef,
    required String inviterRef,
    String name = '',
    String lastName = '',
    String comment = '',
    DateTime? expiresAt,
  }) async {
    final invitation = newInvitation(
      organizationRef: _organizations.current.id,
      roleRef: roleRef,
      inviterRef: inviterRef,
      email: email,
      name: name,
      lastName: lastName,
      comment: comment,
      expiresAt: expiresAt,
    );

    return createObject(_organizations.current.id, invitation.toDTO().toJson());
  }

  Future<void> updateInvitation(Invitation invitation) {
    return update(invitation.toDTO().toJson());
  }

  Future<void> revokeInvitation(Invitation invitation) {
    return updateInvitation(invitation.copyWith(status: InvitationStatus.revoked));
  }

  Future<void> setInvitationArchived(Invitation invitation, bool archived) {
    return setArchived(
      organizationRef: _organizations.current.id,
      objectRef: invitation.id,
      newIsArchived: archived,
    );
  }
}
