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

namespace Indotalent.Features.Inventory.Product.Cqrs;

public class CreateProductRequest
{
    public string? Name { get; set; }
    public string? Description { get; set; }
    public decimal? UnitPrice { get; set; }
    public bool? Physical { get; set; } = true;
    public string? UnitMeasureId { get; set; }
    public string? ProductGroupId { get; set; }
}

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

public record CreateProductCommand(CreateProductRequest Data) : IRequest<CreateProductResponse>;

public class CreateProductHandler : IRequestHandler<CreateProductCommand, CreateProductResponse>
{
    private readonly AppDbContext _context;

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

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

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

        var entityName = nameof(Data.Entities.Product);

        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.Product
        {
            AutoNumber = autoNo,
            Name = request.Data.Name,
            Description = request.Data.Description,
            UnitPrice = request.Data.UnitPrice,
            Physical = request.Data.Physical,
            UnitMeasureId = request.Data.UnitMeasureId,
            ProductGroupId = request.Data.ProductGroupId
        };

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

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