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

namespace Indotalent.Features.Thirdparty.VendorCategory.Cqrs;

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

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

public record CreateVendorCategoryCommand(CreateVendorCategoryRequest Data) : IRequest<CreateVendorCategoryResponse>;

public class CreateVendorCategoryHandler : IRequestHandler<CreateVendorCategoryCommand, CreateVendorCategoryResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

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

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