package credentiallease

import iop "iop/proto/gen/iop"

func (e *Envelope) ToProto() *iop.SignedCredentialLease {
	if e == nil {
		return nil
	}
	return &iop.SignedCredentialLease{
		Version: e.Version, IssuerKeyId: e.IssuerKeyID,
		Scope: &iop.CredentialLeaseScope{
			LeaseId: e.Scope.LeaseID, PrincipalRef: e.Scope.PrincipalRef,
			CredentialSlotRef: e.Scope.CredentialSlotRef, RouteId: e.Scope.RouteID,
			ProfileId: e.Scope.ProfileID, UpstreamTarget: e.Scope.UpstreamTarget,
			NodeId: e.Scope.NodeID, RecipientKeyId: e.Scope.RecipientKeyID,
			HeaderName: e.Scope.HeaderName, Scheme: e.Scope.Scheme,
			CredentialRevision: e.Scope.CredentialRevision, RouteRevision: e.Scope.RouteRevision,
			ProjectionGeneration: e.Scope.ProjectionGeneration,
			IssuedAtUnixNano:     e.Scope.IssuedAtUnixNano, ExpiresAtUnixNano: e.Scope.ExpiresAtUnixNano,
		},
		EphemeralPublicKey: append([]byte(nil), e.EphemeralPublicKey...),
		Nonce:              append([]byte(nil), e.Nonce...), Ciphertext: append([]byte(nil), e.Ciphertext...),
		Signature: append([]byte(nil), e.Signature...),
	}
}

func FromProto(in *iop.SignedCredentialLease) (*Envelope, error) {
	if in == nil || in.GetScope() == nil {
		return nil, ErrInvalid
	}
	s := in.GetScope()
	return &Envelope{
		Version: in.GetVersion(), IssuerKeyID: in.GetIssuerKeyId(),
		Scope: Scope{
			LeaseID: s.GetLeaseId(), PrincipalRef: s.GetPrincipalRef(),
			CredentialSlotRef: s.GetCredentialSlotRef(), RouteID: s.GetRouteId(),
			ProfileID: s.GetProfileId(), UpstreamTarget: s.GetUpstreamTarget(),
			NodeID: s.GetNodeId(), RecipientKeyID: s.GetRecipientKeyId(),
			HeaderName: s.GetHeaderName(), Scheme: s.GetScheme(),
			CredentialRevision: s.GetCredentialRevision(), RouteRevision: s.GetRouteRevision(),
			ProjectionGeneration: s.GetProjectionGeneration(),
			IssuedAtUnixNano:     s.GetIssuedAtUnixNano(), ExpiresAtUnixNano: s.GetExpiresAtUnixNano(),
		},
		EphemeralPublicKey: append([]byte(nil), in.GetEphemeralPublicKey()...),
		Nonce:              append([]byte(nil), in.GetNonce()...), Ciphertext: append([]byte(nil), in.GetCiphertext()...),
		Signature: append([]byte(nil), in.GetSignature()...),
	}, nil
}

func ExpectedFromProto(in *iop.CredentialLeaseBinding) ExpectedScope {
	if in == nil {
		return ExpectedScope{}
	}
	return ExpectedScope{
		PrincipalRef: in.GetPrincipalRef(), CredentialSlotRef: in.GetCredentialSlotRef(),
		RouteID: in.GetRouteId(), ProfileID: in.GetProfileId(), UpstreamTarget: in.GetUpstreamTarget(),
		NodeID: in.GetNodeId(), RecipientKeyID: in.GetRecipientKeyId(),
		CredentialRevision: in.GetCredentialRevision(), RouteRevision: in.GetRouteRevision(),
		ProjectionGeneration: in.GetProjectionGeneration(),
	}
}
