using Books.Api.Domain.ApiKeys.Events;
using EventFlow.Aggregates;

namespace Books.Api.Domain.ApiKeys;

public class ApiKeyAggregate : AggregateRoot<ApiKeyAggregate, ApiKeyId>,
    IEmit<ApiKeyCreatedEvent>,
    IEmit<ApiKeyRevokedEvent>
{
    public new string Name { get; private set; } = string.Empty;
    public string KeyHash { get; private set; } = string.Empty;
    public string CompanyId { get; private set; } = string.Empty;
    public string CreatedBy { get; private set; } = string.Empty;
    public bool IsActive { get; private set; } = true;
    public string? RevokedBy { get; private set; }

    public ApiKeyAggregate(ApiKeyId id) : base(id) { }

    public void Create(string name, string keyHash, string companyId, string createdBy)
    {
        if (!IsNew)
            throw new DomainException("APIKEY_EXISTS", "API key already exists", "API nøgle eksisterer allerede");

        Emit(new ApiKeyCreatedEvent(name, keyHash, companyId, createdBy));
    }

    public void Revoke(string revokedBy)
    {
        if (!IsActive)
            throw new DomainException("APIKEY_REVOKED", "API key is already revoked", "API nøgle er allerede tilbagekaldt");

        Emit(new ApiKeyRevokedEvent(revokedBy));
    }

    public void Apply(ApiKeyCreatedEvent e)
    {
        Name = e.Name;
        KeyHash = e.KeyHash;
        CompanyId = e.CompanyId;
        CreatedBy = e.CreatedBy;
        IsActive = true;
    }

    public void Apply(ApiKeyRevokedEvent e)
    {
        IsActive = false;
        RevokedBy = e.RevokedBy;
    }
}
