import 'package:pshared/data/dto/invitation/invitation.dart';
import 'package:pshared/models/invitation/invitation.dart';
import 'package:pshared/models/invitation/status.dart';
import 'package:pshared/models/organization/bound.dart';
import 'package:pshared/models/permissions/bound.dart';
import 'package:pshared/models/storable.dart';


extension InvitationModelMapper on Invitation {
  InvitationDTO toDTO() => InvitationDTO(
    id: storable.id,
    createdAt: storable.createdAt,
    updatedAt: storable.updatedAt,
    permissionRef: permissionBound.permissionRef,
    organizationRef: permissionBound.organizationRef,
    roleRef: roleRef,
    inviterRef: inviterRef,
    status: _statusToValue(status),
    expiresAt: expiresAt,
    content: InvitationContentDTO(
      email: content.email,
      name: content.name,
      lastName: content.lastName,
      comment: content.comment,
    ),
    isArchived: isArchived,
  );
}

extension InvitationDTOMapper on InvitationDTO {
  Invitation toDomain() => Invitation(
    storable: newStorable(id: id, createdAt: createdAt, updatedAt: updatedAt),
    permissionBound: newPermissionBound(
      organizationBound: newOrganizationBound(organizationRef: organizationRef),
      permissionRef: permissionRef,
    ),
    roleRef: roleRef,
    inviterRef: inviterRef,
    status: _statusFromValue(status),
    expiresAt: expiresAt.toUtc(),
    content: InvitationContent(
      email: content.email,
      name: content.name,
      lastName: content.lastName,
      comment: content.comment,
    ),
    isArchived: isArchived,
  );
}

InvitationStatus _statusFromValue(String value) {
  switch (value) {
    case 'sent':
      return InvitationStatus.sent;
    case 'accepted':
      return InvitationStatus.accepted;
    case 'declined':
      return InvitationStatus.declined;
    case 'revoked':
      return InvitationStatus.revoked;
    case 'created':
    default:
      return InvitationStatus.created;
  }
}

String _statusToValue(InvitationStatus status) {
  switch (status) {
    case InvitationStatus.sent:
      return 'sent';
    case InvitationStatus.accepted:
      return 'accepted';
    case InvitationStatus.declined:
      return 'declined';
    case InvitationStatus.revoked:
      return 'revoked';
    case InvitationStatus.created:
      return 'created';
  }
}
