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

namespace Indotalent.Features.Setting.AutoNumberSequence.Cqrs;

public class UpdateAutoNumberSequenceRequest
{
    public string? Id { get; set; }
    public string? EntityName { get; set; }
    public string? PrefixTemplate { get; set; }
    public string? SuffixTemplate { get; set; }
}

public class UpdateAutoNumberSequenceResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateAutoNumberSequenceCommand(UpdateAutoNumberSequenceRequest Data) : IRequest<UpdateAutoNumberSequenceResponse>;

public class UpdateAutoNumberSequenceHandler : IRequestHandler<UpdateAutoNumberSequenceCommand, UpdateAutoNumberSequenceResponse>
{
    private readonly AppDbContext _context;
    public UpdateAutoNumberSequenceHandler(AppDbContext context) => _context = context;

    public async Task<UpdateAutoNumberSequenceResponse> Handle(UpdateAutoNumberSequenceCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Set<Data.Entities.AutoNumberSequence>()
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return new UpdateAutoNumberSequenceResponse { Id = request.Data.Id, Success = false };

        entity.PrefixTemplate = request.Data.PrefixTemplate;
        entity.SuffixTemplate = request.Data.SuffixTemplate;

        await _context.SaveChangesAsync(cancellationToken);
        return new UpdateAutoNumberSequenceResponse { Id = entity.Id, Success = true };
    }
}