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

namespace Indotalent.Features.Thirdparty.CustomerCategory.Cqrs;

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

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

public record CreateCustomerCategoryCommand(CreateCustomerCategoryRequest Data) : IRequest<CreateCustomerCategoryResponse>;

public class CreateCustomerCategoryHandler : IRequestHandler<CreateCustomerCategoryCommand, CreateCustomerCategoryResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

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

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