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

namespace Indotalent.Features.Inventory.Scrapping.Cqrs;

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

public class GetScrappingByIdResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? ScrappingDate { get; set; }
    public Data.Enums.ScrappingStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseId { get; set; }
    public string? WarehouseName { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
    public List<ScrappingItemResponse> Items { get; set; } = new();
}

public record GetScrappingByIdQuery(string Id) : IRequest<GetScrappingByIdResponse?>;

public class GetScrappingByIdHandler : IRequestHandler<GetScrappingByIdQuery, GetScrappingByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetScrappingByIdHandler(AppDbContext context) => _context = context;

    public async Task<GetScrappingByIdResponse?> Handle(GetScrappingByIdQuery request, CancellationToken cancellationToken)
    {
        var master = await _context.Scrapping
            .AsNoTracking()
            .Include(x => x.Warehouse)
            .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.Scrapping))
            .Select(x => new ScrappingItemResponse
            {
                Id = x.Id,
                ProductId = x.ProductId,
                ProductName = x.Product!.Name,
                Movement = x.Movement
            }).ToListAsync(cancellationToken);

        return new GetScrappingByIdResponse
        {
            Id = master.Id,
            AutoNumber = master.AutoNumber,
            ScrappingDate = master.ScrappingDate,
            Status = master.Status,
            Description = master.Description,
            WarehouseId = master.WarehouseId,
            WarehouseName = master.Warehouse?.Name,
            CreatedAt = master.CreatedAt,
            CreatedBy = master.CreatedBy,
            UpdatedAt = master.UpdatedAt,
            UpdatedBy = master.UpdatedBy,
            Items = items
        };
    }
}