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

namespace Indotalent.Features.Inventory.UnitMeasure.Cqrs;

public class UpdateUnitMeasureRequest
{
    public string? Id { get; set; }
    public string? Name { 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 UpdateUnitMeasureResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateUnitMeasureCommand(UpdateUnitMeasureRequest Data) : IRequest<UpdateUnitMeasureResponse>;

public class UpdateUnitMeasureHandler : IRequestHandler<UpdateUnitMeasureCommand, UpdateUnitMeasureResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<UpdateUnitMeasureResponse> Handle(UpdateUnitMeasureCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.UnitMeasure
            .AnyAsync(x => x.Name == request.Data.Name && x.Id != request.Data.Id, cancellationToken);

        if (isExists)
        {
            throw new AlreadyExistsException("Unit of Measure", request.Data.Name ?? string.Empty);
        }

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

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

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

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