using System.ComponentModel.DataAnnotations.Schema;
using Books.Api.Domain.ApiKeys;
using Books.Api.Domain.ApiKeys.Events;
using EventFlow.Aggregates;
using EventFlow.PostgreSql.ReadStores.Attributes;
using EventFlow.ReadStores;

namespace Books.Api.EventFlow.ReadModels;

[Table("apikey_read_models")]
public class ApiKeyReadModel : IReadModel,
    IAmReadModelFor<ApiKeyAggregate, ApiKeyId, ApiKeyCreatedEvent>,
    IAmReadModelFor<ApiKeyAggregate, ApiKeyId, ApiKeyRevokedEvent>
{
    [PostgreSqlReadModelIdentityColumn]
    public string AggregateId { get; set; } = string.Empty;

    public DateTimeOffset CreateTime { get; set; }
    public DateTimeOffset UpdatedTime { get; set; }

    [PostgreSqlReadModelVersionColumn]
    public int LastAggregateSequenceNumber { get; set; }

    public string Name { get; set; } = string.Empty;
    public string KeyHash { get; set; } = string.Empty;
    public string CompanyId { get; set; } = string.Empty;
    public string CreatedBy { get; set; } = string.Empty;
    public bool IsActive { get; set; } = true;
    public DateTimeOffset? RevokedTime { get; set; }
    public string? RevokedBy { get; set; }

    public Task ApplyAsync(
        IReadModelContext context,
        IDomainEvent<ApiKeyAggregate, ApiKeyId, ApiKeyCreatedEvent> domainEvent,
        CancellationToken cancellationToken)
    {
        var e = domainEvent.AggregateEvent;
        AggregateId = domainEvent.AggregateIdentity.Value;
        CreateTime = domainEvent.Timestamp;
        UpdatedTime = domainEvent.Timestamp;
        LastAggregateSequenceNumber = (int)domainEvent.AggregateSequenceNumber;
        Name = e.Name;
        KeyHash = e.KeyHash;
        CompanyId = e.CompanyId;
        CreatedBy = e.CreatedBy;
        IsActive = true;
        return Task.CompletedTask;
    }

    public Task ApplyAsync(
        IReadModelContext context,
        IDomainEvent<ApiKeyAggregate, ApiKeyId, ApiKeyRevokedEvent> domainEvent,
        CancellationToken cancellationToken)
    {
        var e = domainEvent.AggregateEvent;
        UpdatedTime = domainEvent.Timestamp;
        LastAggregateSequenceNumber = (int)domainEvent.AggregateSequenceNumber;
        IsActive = false;
        RevokedTime = domainEvent.Timestamp;
        RevokedBy = e.RevokedBy;
        return Task.CompletedTask;
    }
}

public class ApiKeyReadModelLocator : IReadModelLocator
{
    public IEnumerable<string> GetReadModelIds(IDomainEvent domainEvent)
    {
        if (domainEvent.GetAggregateEvent() is IAggregateEvent<ApiKeyAggregate, ApiKeyId>)
        {
            yield return domainEvent.GetIdentity().Value;
        }
    }
}
