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

namespace Indotalent.Features.Inventory.UnitMeasure.Cqrs;

public class CreateUnitMeasureRequest
{
    public string? Name { get; set; }
    public string? Description { get; set; }
}

public class CreateUnitMeasureResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateUnitMeasureCommand(CreateUnitMeasureRequest Data) : IRequest<CreateUnitMeasureResponse>;

public class CreateUnitMeasureHandler : IRequestHandler<CreateUnitMeasureCommand, CreateUnitMeasureResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateUnitMeasureResponse> Handle(CreateUnitMeasureCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.UnitMeasure
            .AnyAsync(x => x.Name == request.Data.Name, cancellationToken);

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

        var entity = new Data.Entities.UnitMeasure
        {
            Name = request.Data.Name,
            Description = request.Data.Description
        };

        _context.UnitMeasure.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateUnitMeasureResponse
        {
            Id = entity.Id,
            Name = entity.Name
        };
    }
}