using ERPCore.Domain;
using ERPCore.Domain.Entities;
using ERPCore.Domain.Enums;
using ERPCore.Dtos.Stock;
using ERPCore.Infra.Auth;
using ERPCore.Infra.UoW;
using ERPCore.Repositories.Interfaces;
using ERPCore.Services.Interfaces;
using ERPCore.System.Errors;
using Microsoft.EntityFrameworkCore;

namespace ERPCore.Services;

/// <summary>
/// Stock-adjustment service — the highest-risk feature (02-SECURITY C.5). Auto-posts
/// with a mandatory reason code and user stamp. Line application (FIFO consume on a
/// decrease, layer create on an increase) + ledger posting is delegated to
/// <see cref="IStockMutator"/>. Runs in a single UoW transaction (NFR-02/05).
/// </summary>
public sealed class AdjustmentService : IAdjustmentService
{
    private readonly IRepository<StockAdjustment> _adjustments;
    private readonly IRepository<Warehouse> _warehouses;
    private readonly IRepository<Item> _items;
    private readonly IRepository<ReasonCode> _reasonCodes;
    private readonly IStockMutator _mutator;
    private readonly INumberSequenceService _numbers;
    private readonly ICurrentUser _currentUser;
    private readonly IUnitOfWork _uow;

    public AdjustmentService(
        IRepository<StockAdjustment> adjustments, IRepository<Warehouse> warehouses, IRepository<Item> items,
        IRepository<ReasonCode> reasonCodes, IStockMutator mutator, INumberSequenceService numbers,
        ICurrentUser currentUser, IUnitOfWork uow)
    {
        _adjustments = adjustments;
        _warehouses = warehouses;
        _items = items;
        _reasonCodes = reasonCodes;
        _mutator = mutator;
        _numbers = numbers;
        _currentUser = currentUser;
        _uow = uow;
    }

    public async Task<AdjustmentDto> CreateAsync(CreateAdjustmentRequest request, CancellationToken ct = default)
    {
        if (request.ReasonCodeId is null)
            throw new DomainException(ErrorCodes.ReasonCodeRequired, "A reason code is required for an adjustment.", 400);

        if (!await _warehouses.Query().AnyAsync(w => w.WarehouseId == request.WarehouseId, ct))
            throw new DomainException(ErrorCodes.Validation, $"Warehouse {request.WarehouseId} does not exist.", 422);

        var reason = await _reasonCodes.Query().AsNoTracking().FirstOrDefaultAsync(r => r.ReasonCodeId == request.ReasonCodeId, ct)
            ?? throw new DomainException(ErrorCodes.Validation, $"Reason code {request.ReasonCodeId} does not exist.", 422);
        if (reason.Context != ReasonContext.Adjustment)
            throw new DomainException(ErrorCodes.Validation, $"Reason code {request.ReasonCodeId} is not an Adjustment reason.", 422);

        foreach (var line in request.Lines)
        {
            if (line.QtyDelta == 0)
                throw new DomainException(ErrorCodes.Validation, "qtyDelta cannot be zero.", 422);
            if (!await _items.Query().AnyAsync(i => i.ItemId == line.ItemId, ct))
                throw new DomainException(ErrorCodes.Validation, $"Item {line.ItemId} does not exist.", 422);
        }

        var now = DateTime.UtcNow;
        var deltas = request.Lines
            .Select(l => new StockDelta(l.ItemId, l.BinId, l.BatchId, l.QtyDelta)).ToList();

        var (adjustment, ledgerRefs) = await _uow.ExecuteInTransactionAsync(async token =>
        {
            var docNo = await _numbers.NextAsync(DocumentTypes.Adjustment, token);
            var entity = new StockAdjustment
            {
                DocNo = docNo,
                WarehouseId = request.WarehouseId,
                ReasonCodeId = request.ReasonCodeId.Value,
                Status = AdjustmentStatus.Posted,
                CreatedBy = _currentUser.AuditUserId,
                CreatedAt = now,
                Lines = request.Lines.Select(l => new StockAdjustmentLine
                {
                    ItemId = l.ItemId,
                    BinId = l.BinId,
                    BatchId = l.BatchId,
                    QtyDelta = l.QtyDelta
                }).ToList()
            };
            await _adjustments.AddAsync(entity, token);
            await _uow.SaveChangesAsync(token); // flush so AdjustmentId is a valid ledger sourceDocId

            var refs = await _mutator.ApplyAsync(request.WarehouseId, DocumentTypes.Adjustment, entity.AdjustmentId, now, deltas, token);
            return (entity, refs);
        }, ct);

        return new AdjustmentDto(
            adjustment.AdjustmentId, adjustment.DocNo, adjustment.WarehouseId, adjustment.ReasonCodeId,
            adjustment.Status, adjustment.CreatedBy, adjustment.CreatedAt,
            adjustment.Lines.OrderBy(l => l.AdjLineId)
                .Select(l => new AdjustmentLineDto(l.AdjLineId, l.ItemId, l.BinId, l.BatchId, l.QtyDelta)).ToList(),
            ledgerRefs.Select(l => l.LedgerId).ToList());
    }
}
