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

namespace Indotalent.Features.Inventory.PositiveAdjustment.Cqrs;

public class PositiveAdjustmentItemResponse
{
    public string? Id { get; set; }
    public string? ProductId { get; set; }
    public string? ProductName { get; set; }
    public string? WarehouseId { get; set; }
    public string? WarehouseName { get; set; }
    public double? Movement { get; set; }
}

public class GetPositiveAdjustmentByIdResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? AdjustmentDate { get; set; }
    public Data.Enums.AdjustmentStatus Status { get; set; }
    public string? Description { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
    public List<PositiveAdjustmentItemResponse> Items { get; set; } = new();
}

public record GetPositiveAdjustmentByIdQuery(string Id) : IRequest<GetPositiveAdjustmentByIdResponse?>;

public class GetPositiveAdjustmentByIdHandler : IRequestHandler<GetPositiveAdjustmentByIdQuery, GetPositiveAdjustmentByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetPositiveAdjustmentByIdHandler(AppDbContext context) => _context = context;

    public async Task<GetPositiveAdjustmentByIdResponse?> Handle(GetPositiveAdjustmentByIdQuery request, CancellationToken cancellationToken)
    {
        var master = await _context.PositiveAdjustment
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

        if (master == null) return null;

        var items = await _context.InventoryTransaction
            .AsNoTracking()
            .Include(x => x.Product)
            .Include(x => x.Warehouse)
            .Where(x => x.ModuleId == request.Id && x.ModuleName == nameof(Data.Entities.PositiveAdjustment))
            .Select(x => new PositiveAdjustmentItemResponse
            {
                Id = x.Id,
                ProductId = x.ProductId,
                ProductName = x.Product!.Name,
                WarehouseId = x.WarehouseId,
                WarehouseName = x.Warehouse!.Name,
                Movement = x.Movement
            }).ToListAsync(cancellationToken);

        return new GetPositiveAdjustmentByIdResponse
        {
            Id = master.Id,
            AutoNumber = master.AutoNumber,
            AdjustmentDate = master.AdjustmentDate,
            Status = master.Status,
            Description = master.Description,
            CreatedAt = master.CreatedAt,
            CreatedBy = master.CreatedBy,
            UpdatedAt = master.UpdatedAt,
            UpdatedBy = master.UpdatedBy,
            Items = items
        };
    }
}