using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Document.GetByCode
{
    public sealed class Handler(IAppDbContext db, ICacheService cache) : IQueryHandler<Query, Response?>
    {
        public async Task<Response?> Handle(Query request, CancellationToken ct)
        {
            var cacheKey = CacheKeys.DocumentByCode(request.Code);
            var cached = await cache.GetAsync<Response>(cacheKey, ct);
            if (cached is not null)
            {
                return cached;
            }

            var document = await db.Document.AsNoTracking().Where(c => c.IsActive).FirstOrDefaultAsync(c => c.Code == request.Code, ct);

            if (document is null)
            {
                return null;
            }

            var response = new Response
            {
                ID = document.ID,
                Code = document.Code,
                Subject = document.Subject,
                Content = document.Content,
                IsActive = document.IsActive,
                UpdatedAt = document.UpdatedAt,
                CreatedAt = document.CreatedAt
            };

            await cache.SetAsync(cacheKey, response, ct);
            return response;
        }
    }
}