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

namespace ERPCore.Services;

/// <summary>
/// Purchase-return service (FR-PROC-08). Auto-posts with a mandatory Return reason
/// code and generates an outbound stock movement via the shared
/// <see cref="IStockMutator"/> (FIFO consume, row-locked; over-return beyond
/// available → STOCK_NEGATIVE_BLOCKED). Single UoW transaction. Also posts a real GL
/// journal entry reversing the Inventory/Clearing lines the original <see cref="Grn"/>
/// posted — reuses <c>Grn</c>'s own account config since it's reversing that posting.
/// </summary>
public sealed class PurchaseReturnService : IPurchaseReturnService
{
    private readonly IRepository<PurchaseReturn> _returns;
    private readonly IRepository<Vendor> _vendors;
    private readonly IRepository<Warehouse> _warehouses;
    private readonly IRepository<Item> _items;
    private readonly IRepository<ReasonCode> _reasonCodes;
    private readonly IRepository<GrnLine> _grnLines;
    private readonly IRepository<StockLedger> _ledger;
    private readonly IStockMutator _mutator;
    private readonly INumberSequenceService _numbers;
    private readonly ICurrentUser _currentUser;
    private readonly IUnitOfWork _uow;
    private readonly IGeneralLedgerService _gl;
    private readonly string _glInventoryAccountCode;
    private readonly string _glClearingAccountCode;

    public PurchaseReturnService(
        IRepository<PurchaseReturn> returns, IRepository<Vendor> vendors, IRepository<Warehouse> warehouses,
        IRepository<Item> items, IRepository<ReasonCode> reasonCodes, IRepository<GrnLine> grnLines,
        IRepository<StockLedger> ledger, IStockMutator mutator, INumberSequenceService numbers,
        ICurrentUser currentUser, IUnitOfWork uow, IGeneralLedgerService gl, IConfiguration configuration)
    {
        _returns = returns;
        _vendors = vendors;
        _warehouses = warehouses;
        _items = items;
        _reasonCodes = reasonCodes;
        _grnLines = grnLines;
        _ledger = ledger;
        _mutator = mutator;
        _numbers = numbers;
        _currentUser = currentUser;
        _uow = uow;
        _gl = gl;
        _glInventoryAccountCode = configuration["Grn:GlInventoryAccountCode"] ?? string.Empty;
        _glClearingAccountCode = configuration["Grn:GlClearingAccountCode"] ?? string.Empty;
    }

    public async Task<PagedResponse<PurchaseReturnSummaryDto>> ListAsync(
        PageQuery query, int? vendorId, int? warehouseId, CancellationToken ct = default)
    {
        var q = _returns.Query().AsNoTracking();

        if (!string.IsNullOrWhiteSpace(query.Q))
        {
            var term = query.Q.Trim();
            q = q.Where(r => EF.Functions.ILike(r.DocNo, $"%{term}%"));
        }
        if (vendorId is not null) q = q.Where(r => r.VendorId == vendorId);
        if (warehouseId is not null) q = q.Where(r => r.WarehouseId == warehouseId);

        var total = await q.CountAsync(ct);
        var rows = await q.OrderByDescending(r => r.ReturnId)
            .Skip(query.Skip).Take(query.PageSize)
            .Select(r => new PurchaseReturnSummaryDto(
                r.ReturnId, r.DocNo, r.VendorId, r.WarehouseId, r.ReasonCodeId, r.Status,
                r.CreatedBy, r.CreatedAt, r.Lines.Count, r.GlJournalNo))
            .ToListAsync(ct);

        return PagedResponse<PurchaseReturnSummaryDto>.Create(rows, query.Page, query.PageSize, total);
    }

    public async Task<PurchaseReturnDto?> GetAsync(int returnId, CancellationToken ct = default)
    {
        var ret = await _returns.Query().AsNoTracking()
            .Include(r => r.Lines)
            .FirstOrDefaultAsync(r => r.ReturnId == returnId, ct);
        if (ret is null) return null;

        // Polymorphic ledger reference (docs/10 C.9) — recovered by source-doc lookup.
        var ledgerRefs = await _ledger.Query().AsNoTracking()
            .Where(l => l.SourceDocType == DocumentTypes.PurchaseReturn && l.SourceDocId == returnId)
            .OrderBy(l => l.LedgerId)
            .Select(l => l.LedgerId)
            .ToListAsync(ct);

        return ToDto(ret, ledgerRefs);
    }

    public async Task<PurchaseReturnDto> CreateAsync(CreatePurchaseReturnRequest request, CancellationToken ct = default)
    {
        if (request.ReasonCodeId is null)
            throw new DomainException(ErrorCodes.ReasonCodeRequired, "A reason code is required for a purchase return.", 400);

        if (!await _vendors.Query().AnyAsync(v => v.VendorId == request.VendorId, ct))
            throw new DomainException(ErrorCodes.Validation, $"Vendor {request.VendorId} does not exist.", 422);
        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.Return)
            throw new DomainException(ErrorCodes.Validation, $"Reason code {request.ReasonCodeId} is not a Return reason.", 422);

        foreach (var line in request.Lines)
        {
            if (!await _items.Query().AnyAsync(i => i.ItemId == line.ItemId, ct))
                throw new DomainException(ErrorCodes.Validation, $"Item {line.ItemId} does not exist.", 422);
            if (line.GrnLineId is not null)
            {
                var grnLine = await _grnLines.Query().AsNoTracking().FirstOrDefaultAsync(g => g.GrnLineId == line.GrnLineId, ct)
                    ?? throw new DomainException(ErrorCodes.Validation, $"GRN line {line.GrnLineId} does not exist.", 422);
                if (grnLine.ItemId != line.ItemId)
                    throw new DomainException(ErrorCodes.Validation, $"GRN line {line.GrnLineId} is for a different item.", 422);
            }
        }

        var now = DateTime.UtcNow;
        var deltas = request.Lines.Select(l => new StockDelta(l.ItemId, null, null, -l.Qty)).ToList();

        var (entity, ledgerEntries) = await _uow.ExecuteInTransactionAsync(async token =>
        {
            var docNo = await _numbers.NextAsync(DocumentTypes.PurchaseReturn, token);
            var ret = new PurchaseReturn
            {
                DocNo = docNo,
                VendorId = request.VendorId,
                WarehouseId = request.WarehouseId,
                ReasonCodeId = request.ReasonCodeId.Value,
                Status = ReturnStatus.Posted,
                CreatedBy = _currentUser.AuditUserId,
                CreatedAt = now,
                Lines = request.Lines.Select(l => new PurchaseReturnLine
                {
                    GrnLineId = l.GrnLineId,
                    ItemId = l.ItemId,
                    Qty = l.Qty
                }).ToList()
            };
            await _returns.AddAsync(ret, token);
            await _uow.SaveChangesAsync(token); // flush for a valid ledger sourceDocId

            var refs = await _mutator.ApplyAsync(request.WarehouseId, DocumentTypes.PurchaseReturn, ret.ReturnId, now, deltas, token);

            var totalValue = refs.Sum(r => r.Value);
            if (totalValue > 0)
            {
                var period = await _gl.GetPeriodByDateAsync(DateOnly.FromDateTime(now), token);
                var glResult = await _gl.PostJournalEntryAsync(new GlJournalEntryRequest
                {
                    PeriodId = period.PeriodId,
                    EntryDate = DateOnly.FromDateTime(now),
                    SourceModule = "PURCHASE-RETURN",
                    Reference = docNo,
                    Narration = $"Purchase return {docNo} — stock returned to vendor",
                    Lines = new List<GlJournalEntryLineRequest>
                    {
                        new(_glClearingAccountCode, totalValue, 0m, $"Purchase return {docNo}"),
                        new(_glInventoryAccountCode, 0m, totalValue, $"Purchase return {docNo} — inventory reduction")
                    }
                }, token);
                ret.GlJournalNo = glResult.JournalNo;
                ret.GlPostedAt = now;
            }

            return (ret, refs);
        }, ct);

        // Map ledger ids after commit so they are populated.
        return ToDto(entity, ledgerEntries.Select(r => r.LedgerId).ToList());
    }

    private static PurchaseReturnDto ToDto(PurchaseReturn r, IReadOnlyList<int> ledgerRefs) => new(
        r.ReturnId, r.DocNo, r.VendorId, r.WarehouseId, r.ReasonCodeId, r.Status, r.CreatedBy, r.CreatedAt,
        r.GlJournalNo, r.GlPostedAt,
        r.Lines.OrderBy(l => l.ReturnLineId)
            .Select(l => new PurchaseReturnLineDto(l.ReturnLineId, l.GrnLineId, l.ItemId, l.Qty)).ToList(),
        ledgerRefs);
}
