using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Setting.AutoNumberSequence.Cqrs;

public record GetAutoNumberSequenceByIdResponse(
    string Id, string EntityName, int? Year, int? Month,
    long CurrentSequence, string PrefixTemplate, string SuffixTemplate, int PaddingLength);

public record GetAutoNumberSequenceByIdQuery(string Id) : IRequest<GetAutoNumberSequenceByIdResponse?>;

public class GetAutoNumberSequenceByIdHandler : IRequestHandler<GetAutoNumberSequenceByIdQuery, GetAutoNumberSequenceByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetAutoNumberSequenceByIdHandler(AppDbContext context) => _context = context;

    public async Task<GetAutoNumberSequenceByIdResponse?> Handle(GetAutoNumberSequenceByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Set<Data.Entities.AutoNumberSequence>()
            .AsNoTracking()
            .Where(x => x.Id == request.Id)
            .Select(x => new GetAutoNumberSequenceByIdResponse(
                x.Id, x.EntityName ?? "", x.Year, x.Month,
                x.CurrentSequence ?? 0, x.PrefixTemplate ?? "", x.SuffixTemplate ?? "", x.PaddingLength ?? 0))
            .FirstOrDefaultAsync(cancellationToken);
    }
}