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

namespace Indotalent.Features.Thirdparty.VendorGroup.Cqrs;

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

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

public record CreateVendorGroupCommand(CreateVendorGroupRequest Data) : IRequest<CreateVendorGroupResponse>;

public class CreateVendorGroupHandler : IRequestHandler<CreateVendorGroupCommand, CreateVendorGroupResponse>
{
    private readonly AppDbContext _context;

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

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

        if (isExists)
        {
            throw new AlreadyExistsException("Vendor Group", request.Data.Name ?? string.Empty);
        }


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

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

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