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

namespace Indotalent.Features.Setting.AutoNumberSequence.Cqrs;

public class GetAutoNumberSequenceListResponse
{
    public string? Id { get; set; }
    public string? EntityName { get; set; }
    public int? Year { get; set; }
    public int? Month { get; set; }
    public long? CurrentSequence { get; set; }
    public string? PrefixTemplate { get; set; }
    public string? SuffixTemplate { get; set; }
    public int? PaddingLength { get; set; }
}

public record GetAutoNumberSequenceListQuery() : IRequest<List<GetAutoNumberSequenceListResponse>>;

public class GetAutoNumberSequenceListHandler : IRequestHandler<GetAutoNumberSequenceListQuery, List<GetAutoNumberSequenceListResponse>>
{
    private readonly AppDbContext _context;

    public GetAutoNumberSequenceListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetAutoNumberSequenceListResponse>> Handle(GetAutoNumberSequenceListQuery request, CancellationToken cancellationToken)
    {
        return await _context.AutoNumberSequence
            .AsNoTracking()
            .OrderBy(x => x.EntityName)
            .Select(x => new GetAutoNumberSequenceListResponse
            {
                Id = x.Id,
                EntityName = x.EntityName,
                Year = x.Year,
                Month = x.Month,
                CurrentSequence = x.CurrentSequence,
                PrefixTemplate = x.PrefixTemplate,
                SuffixTemplate = x.SuffixTemplate,
                PaddingLength = x.PaddingLength
            })
            .ToListAsync(cancellationToken);
    }
}