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

namespace Indotalent.Features.Inventory.Product.Cqrs;

public class GetProductByIdResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { 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 record GetProductByIdQuery(string Id) : IRequest<GetProductByIdResponse?>;

public class GetProductByIdHandler : IRequestHandler<GetProductByIdQuery, GetProductByIdResponse?>
{
    private readonly AppDbContext _context;

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

    public async Task<GetProductByIdResponse?> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Product
            .AsNoTracking()
            .Where(x => x.Id == request.Id)
            .Select(x => new GetProductByIdResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                Description = x.Description,
                UnitPrice = x.UnitPrice,
                Physical = x.Physical,
                UnitMeasureId = x.UnitMeasureId,
                ProductGroupId = x.ProductGroupId,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy,
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}