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

namespace Indotalent.Features.Setting.Tax.Cqrs;

public class UpdateTaxRequest
{
    public string? Id { get; set; }
    public string? Code { get; set; }
    public string? Name { get; set; }
    public decimal PercentageValue { get; set; }
    public string? Category { get; set; }
    public string? Description { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateTaxCommand(UpdateTaxRequest Data) : IRequest<UpdateTaxResponse>;

public class UpdateTaxHandler : IRequestHandler<UpdateTaxCommand, UpdateTaxResponse>
{
    private readonly AppDbContext _context;

    public UpdateTaxHandler(AppDbContext context)
    {
        _context = context;
    }

    public async Task<UpdateTaxResponse> Handle(UpdateTaxCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.Tax
            .AnyAsync(x => x.Code == request.Data.Code && x.Id != request.Data.Id, cancellationToken);

        if (isExists)
        {
            throw new AlreadyExistsException("Tax", request.Data.Code ?? string.Empty);
        }

        var entity = await _context.Tax
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

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

        entity.Code = request.Data.Code;
        entity.Name = request.Data.Name;
        entity.PercentageValue = request.Data.PercentageValue;
        entity.Category = request.Data.Category;
        entity.Description = request.Data.Description;
        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateTaxResponse
        {
            Id = entity.Id,
            Success = true
        };
    }
}