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

namespace Indotalent.Features.Inventory.TransferIn.Cqrs;

public class TransferInItemResponse
{
    public string? Id { get; set; }
    public string? ProductId { get; set; }
    public string? ProductName { get; set; }
    public double? Movement { get; set; }
}

public class GetTransferInByIdResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? TransferReceiveDate { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
    public string? Description { get; set; }
    public string? TransferOutId { get; set; }
    public string? TransferOutNumber { get; set; }
    public string? WarehouseToName { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
    public List<TransferInItemResponse> Items { get; set; } = new();
}

public record GetTransferInByIdQuery(string Id) : IRequest<GetTransferInByIdResponse?>;

public class GetTransferInByIdHandler : IRequestHandler<GetTransferInByIdQuery, GetTransferInByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetTransferInByIdHandler(AppDbContext context) => _context = context;

    public async Task<GetTransferInByIdResponse?> Handle(GetTransferInByIdQuery request, CancellationToken cancellationToken)
    {
        var master = await _context.TransferIn
            .AsNoTracking()
            .Include(x => x.TransferOut)
            .ThenInclude(x => x!.WarehouseTo)
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

        if (master == null) return null;

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

        return new GetTransferInByIdResponse
        {
            Id = master.Id,
            AutoNumber = master.AutoNumber,
            TransferReceiveDate = master.TransferReceiveDate,
            Status = master.Status,
            Description = master.Description,
            TransferOutId = master.TransferOutId,
            TransferOutNumber = master.TransferOut?.AutoNumber,
            WarehouseToName = master.TransferOut?.WarehouseTo?.Name,
            CreatedAt = master.CreatedAt,
            CreatedBy = master.CreatedBy,
            UpdatedAt = master.UpdatedAt,
            UpdatedBy = master.UpdatedBy,
            Items = items
        };
    }
}