<?php

declare(strict_types=1);

namespace App\Business\Purchase;

use App\Business\Inventory\Enums\InventoryBusinessType;
use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\Exceptions\InsufficientStockException;
use App\Business\Inventory\InventoryLedgerLineTrace;
use App\Business\Inventory\InventoryLedgerService;
use App\Business\Inventory\InventoryRefinementService;
use App\Business\Inventory\InventoryRuleService;
use App\Business\Product\DberpProductUnitConversionService;
use App\Business\Product\InventoryPostingProductSkuResolver;
use App\Business\Settlement\PayableService;
use App\Models\DberpInventoryBalance;
use App\Models\DberpProductSku;
use App\Models\DberpPurchaseReturnOrder;
use App\Models\DberpPurchaseReturnOrderItem;
use App\Services\DberpAuditService;
use App\Support\DberpAuditTrailGuard;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

final class PurchaseReturnService
{
    public function __construct(
        private readonly InventoryLedgerService $ledgerService,
        private readonly InventoryRefinementService $refinementService,
        private readonly InventoryRuleService $ruleService,
        private readonly PayableService $payableService,
        private readonly DberpAuditService $auditService,
    ) {}

    public function apply(DberpPurchaseReturnOrder $order): void
    {
        try {
            DB::transaction(function () use ($order): void {
                $locked = DberpPurchaseReturnOrder::query()->whereKey($order->getKey())->lockForUpdate()->firstOrFail();
                $locked->loadMissing('purchaseOrder', 'purchaseReceiptOrder', 'warehouse');

                if ($locked->status !== InventoryDocumentStatus::Draft->value) {
                    throw ValidationException::withMessages([
                        'status' => __('dberp.errors.inventory_doc_not_draft'),
                    ]);
                }

                $this->validateOrderReference($locked);

                $items = $locked->items()->with(['product', 'purchaseOrderItem.productSku', 'purchaseReceiptItem.productSku'])->orderBy('sort_order')->orderBy('id')->get();

                if ($items->isEmpty()) {
                    throw ValidationException::withMessages([
                        'items' => __('dberp.errors.purchase_return_no_items'),
                    ]);
                }

                if ($locked->warehouse_id === null || $locked->warehouse === null) {
                    throw ValidationException::withMessages([
                        'warehouse_id' => __('dberp.errors.inventory_outbound_line_incomplete'),
                    ]);
                }

                foreach ($items as $item) {
                    if ($locked->purchase_order_id !== null && (int) $item->purchaseOrderItem->order_id !== (int) $locked->purchase_order_id) {
                        throw ValidationException::withMessages([
                            'purchase_order_item_id' => __('dberp.errors.purchase_return_item_order_mismatch'),
                        ]);
                    }

                    if ($item->purchaseReceiptItem !== null && $locked->purchase_receipt_order_id !== null && (int) $item->purchaseReceiptItem->order_id !== (int) $locked->purchase_receipt_order_id) {
                        throw ValidationException::withMessages([
                            'purchase_receipt_item_id' => __('dberp.errors.purchase_return_item_receipt_mismatch'),
                        ]);
                    }

                    if ((int) $item->purchaseOrderItem->product_id !== (int) $item->product_id) {
                        throw ValidationException::withMessages([
                            'product_id' => __('dberp.errors.purchase_item_product_mismatch'),
                        ]);
                    }

                    if ($item->purchaseReceiptItem !== null && (int) $item->purchaseReceiptItem->product_id !== (int) $item->product_id) {
                        throw ValidationException::withMessages([
                            'product_id' => __('dberp.errors.purchase_item_product_mismatch'),
                        ]);
                    }

                    if ($item->purchaseReceiptItem !== null
                        && (int) $item->purchaseReceiptItem->product_sku_id !== (int) $item->purchaseOrderItem->product_sku_id) {
                        throw ValidationException::withMessages([
                            'product_sku_id' => __('dberp.errors.purchase_item_sku_mismatch'),
                        ]);
                    }

                    $ledgerQty = (string) $item->base_return_quantity;
                    $lineTrace = InventoryLedgerLineTrace::fromDocumentLine($item, 'return_quantity');

                    if (bccomp($ledgerQty, '0', 4) !== 1) {
                        throw ValidationException::withMessages([
                            'return_quantity' => __('dberp.errors.purchase_return_quantity_invalid'),
                        ]);
                    }

                    if ($item->purchaseReceiptItem !== null) {
                        $receiptLine = $item->purchaseReceiptItem;
                        $returnableBase = bcsub(
                            (string) ($receiptLine->base_received_quantity ?? '0'),
                            (string) ($receiptLine->base_returned_quantity ?? '0'),
                            4
                        );

                        if (bccomp($ledgerQty, $returnableBase, 4) === 1) {
                            $this->auditService->log(
                                'dberp.purchase_return.quantity_overflow_blocked',
                                $locked,
                                null,
                                [
                                    'purchase_order_item_id' => $item->purchase_order_item_id,
                                    'purchase_receipt_item_id' => $item->purchase_receipt_item_id,
                                    'product_id' => $item->product_id,
                                    'returnable_base' => $returnableBase,
                                    'return_quantity' => (string) $item->return_quantity,
                                    'base_return_quantity' => (string) $item->base_return_quantity,
                                ],
                            );

                            throw ValidationException::withMessages([
                                'return_quantity' => __('dberp.errors.purchase_return_quantity_exceeds_returnable'),
                            ]);
                        }
                    } else {
                        $returnable = (float) $item->purchaseOrderItem->received_quantity - (float) $item->purchaseOrderItem->returned_quantity;

                        if ((float) $item->return_quantity > $returnable) {
                            $this->auditService->log(
                                'dberp.purchase_return.quantity_overflow_blocked',
                                $locked,
                                null,
                                [
                                    'purchase_order_item_id' => $item->purchase_order_item_id,
                                    'purchase_receipt_item_id' => $item->purchase_receipt_item_id,
                                    'product_id' => $item->product_id,
                                    'returnable' => number_format($returnable, 4, '.', ''),
                                    'return_quantity' => (string) $item->return_quantity,
                                ],
                            );

                            throw ValidationException::withMessages([
                                'return_quantity' => __('dberp.errors.purchase_return_quantity_exceeds_returnable'),
                            ]);
                        }
                    }

                    $returnApplyKey = sprintf('purchase_return:%d:confirm:%d', (int) $locked->getKey(), (int) $item->getKey());

                    $sku = $this->resolveProductSkuForPurchaseReturnItem($item);

                    $post = $this->ledgerService->outbound(
                        productSku: $sku,
                        warehouse: $locked->warehouse,
                        quantity: $ledgerQty,
                        businessType: InventoryBusinessType::PurchaseReturn,
                        businessNumber: (string) $locked->code,
                        sourceType: $locked->getMorphClass(),
                        sourceId: (int) $locked->getKey(),
                        remark: $item->remark ?? $locked->remark,
                        businessTime: $locked->business_time ?? now(),
                        idempotencyKey: $returnApplyKey,
                        lineTrace: $lineTrace,
                    );

                    if (! $post->wasIdempotentReplay) {
                        $result = $this->refinementService->applyOutbound(
                            product: $sku->product,
                            warehouse: $locked->warehouse,
                            quantity: $ledgerQty,
                            businessType: InventoryBusinessType::PurchaseReturn,
                            businessNumber: (string) $locked->code,
                            sourceType: $locked->getMorphClass(),
                            sourceId: (int) $locked->getKey(),
                            remark: $item->remark ?? $locked->remark,
                            businessTime: $locked->business_time ?? now(),
                            detail: $this->buildRefinementDetail($item),
                        );

                        $item->forceFill([
                            'source_batch_id' => $result['batch_id'] ?? $item->source_batch_id,
                            'batch_no' => $result['batch_no'] ?? $item->batch_no,
                            'batch_allocations' => $result['batch_allocations'],
                            'serial_numbers' => $result['serial_numbers'],
                        ])->save();

                        $poLine = $item->purchaseOrderItem;
                        $deltaPo = DberpProductUnitConversionService::baseQuantityToLineEnteredString(
                            (string) $item->base_return_quantity,
                            $poLine,
                        );

                        $poLine->forceFill([
                            'returned_quantity' => bcadd((string) $poLine->returned_quantity, $deltaPo, 4),
                        ])->save();

                        if ($item->purchaseReceiptItem !== null) {
                            $receiptLine = $item->purchaseReceiptItem;
                            $deltaReceipt = DberpProductUnitConversionService::baseQuantityToLineEnteredString(
                                (string) $item->base_return_quantity,
                                $receiptLine,
                            );
                            $receiptLine->forceFill([
                                'returned_quantity' => bcadd((string) $receiptLine->returned_quantity, $deltaReceipt, 4),
                                'base_returned_quantity' => bcadd((string) ($receiptLine->base_returned_quantity ?? '0'), (string) $item->base_return_quantity, 4),
                            ])->save();
                        }
                    }
                }

                $this->refreshTotals($locked);

                $before = ['status' => $locked->status, 'effective_at' => $locked->effective_at];

                $this->auditService->logSemanticSave(
                    'dberp.purchase_return.applied',
                    $locked,
                    function () use ($locked): void {
                        $locked->forceFill([
                            'status' => InventoryDocumentStatus::Effective->value,
                            'effective_at' => now(),
                        ])->save();
                    },
                    $before,
                    ['status' => $locked->status, 'effective_at' => $locked->effective_at],
                );

                if ($locked->purchaseOrder !== null) {
                    $this->payableService->refreshForPurchaseOrder(
                        order: $locked->purchaseOrder,
                        changeType: 'purchase_return_applied',
                        remark: $locked->remark,
                        source: $locked,
                        documentNumber: (string) $locked->code,
                        businessTime: $locked->business_time,
                    );
                }
            });
        } catch (InsufficientStockException $exception) {
            $this->auditInsufficientStock($exception);

            throw $exception->validationException();
        }
    }

    public function void(DberpPurchaseReturnOrder $order): void
    {
        DB::transaction(function () use ($order): void {
            $locked = DberpPurchaseReturnOrder::query()->whereKey($order->getKey())->lockForUpdate()->firstOrFail();
            $locked->loadMissing('warehouse');

            if ($locked->status !== InventoryDocumentStatus::Effective->value) {
                throw ValidationException::withMessages([
                    'status' => __('dberp.errors.inventory_doc_not_effective'),
                ]);
            }

            if (! $this->ruleService->allowsEffectiveInventoryVoid()) {
                throw ValidationException::withMessages([
                    'status' => __('dberp.errors.inventory_void_policy_blocked'),
                ]);
            }

            $rollbackInventoryEffects = $this->ruleService->allowVoidRollback();

            if ($rollbackInventoryEffects) {
                $items = $locked->items()->with(['product', 'purchaseOrderItem.productSku', 'purchaseReceiptItem.productSku'])->orderBy('sort_order')->orderBy('id')->get();

                foreach ($items as $item) {
                    $poLine = $item->purchaseOrderItem;
                    $ledgerQty = (string) $item->base_return_quantity;
                    $lineTrace = InventoryLedgerLineTrace::fromDocumentLine($item, 'return_quantity');

                    $ledgerReplayed = false;

                    if (bccomp($ledgerQty, '0', 4) === 1) {
                        $sku = $this->resolveProductSkuForPurchaseReturnItem($item);

                        $returnVoidKey = sprintf('purchase_return:%d:void:%d', (int) $locked->getKey(), (int) $item->getKey());

                        $post = $this->ledgerService->inbound(
                            productSku: $sku,
                            warehouse: $locked->warehouse,
                            quantity: $ledgerQty,
                            businessType: InventoryBusinessType::PurchaseReturnVoid,
                            businessNumber: (string) $locked->code,
                            sourceType: $locked->getMorphClass(),
                            sourceId: (int) $locked->getKey(),
                            remark: $item->remark ?? $locked->remark,
                            businessTime: now(),
                            idempotencyKey: $returnVoidKey,
                            lineTrace: $lineTrace,
                        );

                        $ledgerReplayed = $post->wasIdempotentReplay;

                        if (! $post->wasIdempotentReplay) {
                            $this->refinementService->rollbackOutbound(
                                product: $sku->product,
                                warehouse: $locked->warehouse,
                                quantity: $ledgerQty,
                                businessType: InventoryBusinessType::PurchaseReturnVoid,
                                businessNumber: (string) $locked->code,
                                sourceType: $locked->getMorphClass(),
                                sourceId: (int) $locked->getKey(),
                                remark: $item->remark ?? $locked->remark,
                                businessTime: now(),
                                detail: $this->buildRefinementDetail($item),
                            );
                        }
                    }

                    if (! $ledgerReplayed) {
                        $deltaPo = DberpProductUnitConversionService::baseQuantityToLineEnteredString(
                            (string) $item->base_return_quantity,
                            $poLine,
                        );

                        $poLine->forceFill([
                            'returned_quantity' => bcsub((string) $poLine->returned_quantity, $deltaPo, 4),
                        ])->save();

                        if ($item->purchaseReceiptItem !== null) {
                            $receiptLine = $item->purchaseReceiptItem;
                            $deltaReceipt = DberpProductUnitConversionService::baseQuantityToLineEnteredString(
                                (string) $item->base_return_quantity,
                                $receiptLine,
                            );

                            $receiptLine->forceFill([
                                'returned_quantity' => bcsub((string) $receiptLine->returned_quantity, $deltaReceipt, 4),
                                'base_returned_quantity' => bcsub((string) ($receiptLine->base_returned_quantity ?? '0'), (string) $item->base_return_quantity, 4),
                            ])->save();
                        }
                    }
                }

                if ($locked->purchaseOrder !== null) {
                    $this->payableService->refreshForPurchaseOrder(
                        order: $locked->purchaseOrder,
                        changeType: 'purchase_return_voided',
                        remark: $locked->remark,
                        source: $locked,
                        documentNumber: (string) $locked->code,
                        businessTime: now(),
                    );
                }
            }

            $before = ['status' => $locked->status, 'voided_at' => $locked->voided_at];

            $this->auditService->logSemanticSave(
                'dberp.purchase_return.voided',
                $locked,
                function () use ($locked): void {
                    $locked->forceFill([
                        'status' => InventoryDocumentStatus::Voided->value,
                        'voided_at' => now(),
                    ])->save();
                },
                $before,
                ['status' => $locked->status, 'voided_at' => $locked->voided_at],
            );
        });
    }

    public function refreshTotals(DberpPurchaseReturnOrder $order): void
    {
        $totals = $order->items()->selectRaw('COALESCE(SUM(return_quantity), 0) as total_return_quantity, COALESCE(SUM(return_amount), 0) as total_amount')->first();

        DberpAuditTrailGuard::withoutAuditTrail(function () use ($order, $totals): void {
            $order->forceFill([
                'total_return_quantity' => (string) ($totals?->total_return_quantity ?? '0.0000'),
                'total_amount' => (string) ($totals?->total_amount ?? '0.0000'),
            ])->save();
        });
    }

    private function validateOrderReference(DberpPurchaseReturnOrder $order): void
    {
        if ($order->purchase_order_id === null && $order->purchase_receipt_order_id === null) {
            throw ValidationException::withMessages([
                'purchase_order_id' => __('dberp.errors.purchase_return_reference_required'),
            ]);
        }

        if ($order->purchase_receipt_order_id !== null && $order->purchaseReceiptOrder !== null) {
            $receiptOrder = $order->purchaseReceiptOrder;

            if ($order->purchase_order_id !== null && (int) $receiptOrder->purchase_order_id !== (int) $order->purchase_order_id) {
                throw ValidationException::withMessages([
                    'purchase_receipt_order_id' => __('dberp.errors.purchase_return_reference_mismatch'),
                ]);
            }

            if ((int) $receiptOrder->supplier_id !== (int) $order->supplier_id) {
                throw ValidationException::withMessages([
                    'supplier_id' => __('dberp.errors.purchase_supplier_mismatch'),
                ]);
            }
        }

        if ($order->purchaseOrder !== null && (int) $order->purchaseOrder->supplier_id !== (int) $order->supplier_id) {
            throw ValidationException::withMessages([
                'supplier_id' => __('dberp.errors.purchase_supplier_mismatch'),
            ]);
        }
    }

    private function auditInsufficientStock(InsufficientStockException $exception): void
    {
        $balanceQuery = DberpInventoryBalance::query()->where('warehouse_id', $exception->warehouseId);

        if ($exception->productSkuId !== null) {
            $balanceQuery->where('product_sku_id', $exception->productSkuId);
        } else {
            $balanceQuery->where('product_id', $exception->productId);
        }

        $balance = $balanceQuery->first();

        $this->auditService->log(
            'dberp.inventory.insufficient_stock_blocked',
            $balance,
            null,
            $exception->auditContext(),
        );
    }

    private function resolveProductSkuForPurchaseReturnItem(DberpPurchaseReturnOrderItem $item): DberpProductSku
    {
        $product = $item->product;

        if ($item->product_sku_id !== null && (int) $item->product_sku_id > 0) {
            $sku = InventoryPostingProductSkuResolver::resolveExplicitSkuForProduct($product, (int) $item->product_sku_id);
            $this->assertPurchaseReturnLineSkuMatchesUpstreamSources($item, (int) $sku->getKey());

            return $sku;
        }

        $receiptItem = $item->purchaseReceiptItem;
        if ($receiptItem !== null && $receiptItem->productSku instanceof DberpProductSku) {
            return $receiptItem->productSku;
        }

        $poItem = $item->purchaseOrderItem;
        if ($poItem->productSku instanceof DberpProductSku) {
            return $poItem->productSku;
        }

        return InventoryPostingProductSkuResolver::resolveSkuForPosting($product, null);
    }

    private function assertPurchaseReturnLineSkuMatchesUpstreamSources(DberpPurchaseReturnOrderItem $item, int $resolvedSkuId): void
    {
        $expected = null;
        if ($item->purchaseReceiptItem !== null && $item->purchaseReceiptItem->product_sku_id !== null && (int) $item->purchaseReceiptItem->product_sku_id > 0) {
            $expected = (int) $item->purchaseReceiptItem->product_sku_id;
        } elseif ($item->purchaseOrderItem->product_sku_id !== null && (int) $item->purchaseOrderItem->product_sku_id > 0) {
            $expected = (int) $item->purchaseOrderItem->product_sku_id;
        }

        if ($expected !== null && $expected !== $resolvedSkuId) {
            throw ValidationException::withMessages([
                'items' => (string) __('dberp.errors.purchase_return_line_spec_upstream_mismatch'),
            ]);
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function buildRefinementDetail($item): array
    {
        return [
            'source_batch_id' => $item->source_batch_id ?? $item->purchaseReceiptItem?->source_batch_id,
            'batch_no' => $item->batch_no ?? $item->purchaseReceiptItem?->batch_no,
            'production_date' => $item->production_date?->format('Y-m-d') ?? $item->purchaseReceiptItem?->production_date?->format('Y-m-d'),
            'expiry_date' => $item->expiry_date?->format('Y-m-d') ?? $item->purchaseReceiptItem?->expiry_date?->format('Y-m-d'),
            'shelf_life_days' => (int) ($item->shelf_life_days ?: $item->purchaseReceiptItem?->shelf_life_days ?: 0),
            'batch_allocations' => $item->batch_allocations ?: [],
            'serial_numbers' => $item->serial_numbers,
        ];
    }
}
