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

namespace Indotalent.Features.Inventory.ProductGroup.Cqrs;

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

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

public record CreateProductGroupCommand(CreateProductGroupRequest Data) : IRequest<CreateProductGroupResponse>;

public class CreateProductGroupHandler : IRequestHandler<CreateProductGroupCommand, CreateProductGroupResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

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

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