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

namespace Indotalent.Features.Inventory.Product.Cqrs;

public class UpdateProductRequest
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public decimal? UnitPrice { get; set; }
    public bool? Physical { get; set; }
    public string? UnitMeasureId { get; set; }
    public string? ProductGroupId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public class UpdateProductResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateProductCommand(UpdateProductRequest Data) : IRequest<UpdateProductResponse>;

public class UpdateProductHandler : IRequestHandler<UpdateProductCommand, UpdateProductResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<UpdateProductResponse> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.Product
            .AnyAsync(x => x.Name == request.Data.Name && x.Id != request.Data.Id, cancellationToken);

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

        var entity = await _context.Product
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null)
        {
            return new UpdateProductResponse { Id = request.Data.Id, Success = false };
        }

        entity.Name = request.Data.Name;
        entity.Description = request.Data.Description;
        entity.UnitPrice = request.Data.UnitPrice;
        entity.Physical = request.Data.Physical;
        entity.UnitMeasureId = request.Data.UnitMeasureId;
        entity.ProductGroupId = request.Data.ProductGroupId;

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateProductResponse
        {
            Id = entity.Id,
            Success = true
        };
    }
}