<?php

declare(strict_types=1);

namespace App\Business\Sales;

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\ProductSkuOperationalGuard;
use App\Business\Sales\Enums\SalesOrderStatus;
use App\Models\DberpInventoryBalance;
use App\Models\DberpSalesOutboundOrder;
use App\Services\DberpAuditService;
use App\Support\DberpAuditTrailGuard;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

final class SalesOutboundService
{
    public function __construct(
        private readonly InventoryLedgerService $ledgerService,
        private readonly InventoryRefinementService $refinementService,
        private readonly InventoryRuleService $ruleService,
        private readonly SalesOrderService $salesOrderService,
        private readonly DberpAuditService $auditService,
    ) {}

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

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

                if (! in_array($locked->salesOrder->status, [
                    SalesOrderStatus::Confirmed->value,
                    SalesOrderStatus::PartiallyShipped->value,
                    SalesOrderStatus::FullyShipped->value,
                ], true)) {
                    throw ValidationException::withMessages([
                        'sales_order_id' => __('dberp.errors.sales_order_not_outboundable'),
                    ]);
                }

                if ((int) $locked->salesOrder->customer_id !== (int) $locked->customer_id) {
                    throw ValidationException::withMessages([
                        'customer_id' => __('dberp.errors.sales_customer_mismatch'),
                    ]);
                }

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

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

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

                $preflightLines = [];

                foreach ($items as $item) {
                    if (bccomp((string) $item->base_ship_quantity, '0', 4) !== 1) {
                        continue;
                    }

                    $sku = $item->productSku;
                    if ($sku === null) {
                        continue;
                    }

                    $preflightLines[] = [
                        'sku' => $sku,
                        'warehouse' => $locked->warehouse,
                        'quantity' => (string) $item->base_ship_quantity,
                    ];
                }

                if ($preflightLines !== []) {
                    $this->ledgerService->assertNoOutboundShortagesPreflight(
                        $preflightLines,
                        InventoryBusinessType::SalesOutbound,
                        (string) $locked->code,
                    );
                }

                foreach ($items as $item) {
                    if ((int) $item->salesOrderItem->order_id !== (int) $locked->sales_order_id) {
                        throw ValidationException::withMessages([
                            'sales_order_item_id' => __('dberp.errors.sales_outbound_item_order_mismatch'),
                        ]);
                    }

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

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

                    $soLine = $item->salesOrderItem;

                    $remainingBase = bcsub(
                        (string) ($soLine->base_quantity ?? '0'),
                        (string) ($soLine->base_shipped_quantity ?? '0'),
                        4
                    );

                    if (bccomp((string) $item->base_ship_quantity, '0', 4) !== 1) {
                        throw ValidationException::withMessages([
                            'ship_quantity' => __('dberp.errors.sales_outbound_quantity_invalid'),
                        ]);
                    }

                    if (bccomp((string) $item->base_ship_quantity, $remainingBase, 4) === 1) {
                        $this->auditService->log(
                            'dberp.sales_outbound.quantity_overflow_blocked',
                            $locked,
                            null,
                            [
                                'sales_order_item_id' => $item->sales_order_item_id,
                                'product_id' => $item->product_id,
                                'remaining_base' => $remainingBase,
                                'ship_quantity' => (string) $item->ship_quantity,
                                'base_ship_quantity' => (string) $item->base_ship_quantity,
                            ],
                        );

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

                    $sku = $item->productSku;
                    if ($sku === null) {
                        throw ValidationException::withMessages([
                            'product_sku_id' => __('dberp.errors.sales_outbound_item_sku_required'),
                        ]);
                    }

                    ProductSkuOperationalGuard::assertEnabledForSale($sku);

                    $outboundLineKey = sprintf('sales_outbound:%d:confirm:%d', (int) $locked->getKey(), (int) $item->getKey());
                    $ledgerQty = (string) $item->base_ship_quantity;
                    $lineTrace = InventoryLedgerLineTrace::fromDocumentLine($item, 'ship_quantity');

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

                    if (! $post->wasIdempotentReplay) {
                        $result = $this->refinementService->applyOutbound(
                            product: $sku->product,
                            warehouse: $locked->warehouse,
                            quantity: $ledgerQty,
                            businessType: InventoryBusinessType::SalesOutbound,
                            businessNumber: (string) $locked->code,
                            sourceType: $locked->getMorphClass(),
                            sourceId: (int) $locked->getKey(),
                            remark: $item->remark ?? $locked->remark,
                            businessTime: $locked->business_time ?? now(),
                            detail: [
                                'source_batch_id' => $item->source_batch_id,
                                'batch_no' => $item->batch_no,
                                'batch_allocations' => $item->batch_allocations ?: [],
                                'serial_numbers' => $item->serial_numbers,
                            ],
                            enforceSaleExpiry: true,
                        );

                        $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();
                    }

                    if (! $post->wasIdempotentReplay) {
                        $deltaShipSo = DberpProductUnitConversionService::baseQuantityToLineEnteredString(
                            (string) $item->base_ship_quantity,
                            $soLine,
                        );
                        $newShipped = bcadd((string) $soLine->shipped_quantity, $deltaShipSo, 4);
                        $newBaseShipped = bcadd((string) ($soLine->base_shipped_quantity ?? '0'), (string) $item->base_ship_quantity, 4);

                        $soLine->forceFill([
                            'shipped_quantity' => $newShipped,
                            'base_shipped_quantity' => $newBaseShipped,
                        ])->save();
                    }
                }

                $this->refreshTotals($locked);

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

                $this->auditService->logSemanticSave(
                    'dberp.sales_outbound.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],
                );

                $this->salesOrderService->refreshTotals($locked->salesOrder);
                $this->salesOrderService->syncOutboundStatus($locked->salesOrder);
            });
        } catch (InsufficientStockException $exception) {
            $this->auditInsufficientStock($exception);

            throw $exception->validationException();
        }
    }

    public function void(DberpSalesOutboundOrder $order): void
    {
        DB::transaction(function () use ($order): void {
            $locked = DberpSalesOutboundOrder::query()->whereKey($order->getKey())->lockForUpdate()->firstOrFail();
            $locked->loadMissing('salesOrder', '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', 'productSku', 'salesOrderItem.productSku'])->orderBy('sort_order')->orderBy('id')->get();

                foreach ($items as $item) {
                    if ((float) $item->returned_quantity > 0) {
                        throw ValidationException::withMessages([
                            'status' => __('dberp.errors.sales_outbound_has_returns'),
                        ]);
                    }

                    $soLine = $item->salesOrderItem;
                    $ledgerQty = (string) $item->base_ship_quantity;
                    $lineTrace = InventoryLedgerLineTrace::fromDocumentLine($item, 'ship_quantity');

                    $ledgerReplayed = false;

                    if (bccomp($ledgerQty, '0', 4) === 1) {
                        $sku = $item->productSku;
                        if ($sku === null) {
                            throw ValidationException::withMessages([
                                'product_sku_id' => __('dberp.errors.sales_outbound_item_sku_required'),
                            ]);
                        }

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

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

                        $ledgerReplayed = $post->wasIdempotentReplay;

                        if (! $post->wasIdempotentReplay) {
                            $this->refinementService->rollbackOutbound(
                                product: $sku->product,
                                warehouse: $locked->warehouse,
                                quantity: $ledgerQty,
                                businessType: InventoryBusinessType::SalesOutboundVoid,
                                businessNumber: (string) $locked->code,
                                sourceType: $locked->getMorphClass(),
                                sourceId: (int) $locked->getKey(),
                                remark: $item->remark ?? $locked->remark,
                                businessTime: now(),
                                detail: [
                                    'source_batch_id' => $item->source_batch_id,
                                    'batch_no' => $item->batch_no,
                                    'batch_allocations' => $item->batch_allocations ?: [],
                                    'serial_numbers' => $item->serial_numbers,
                                ],
                            );
                        }
                    }

                    if (! $ledgerReplayed) {
                        $deltaShipSo = DberpProductUnitConversionService::baseQuantityToLineEnteredString(
                            (string) $item->base_ship_quantity,
                            $soLine,
                        );
                        $newShipped = bcsub((string) $soLine->shipped_quantity, $deltaShipSo, 4);
                        $newBaseShipped = bcsub((string) ($soLine->base_shipped_quantity ?? '0'), (string) $item->base_ship_quantity, 4);

                        $soLine->forceFill([
                            'shipped_quantity' => $newShipped,
                            'base_shipped_quantity' => $newBaseShipped,
                        ])->save();
                    }
                }

                $this->salesOrderService->refreshTotals($locked->salesOrder);
                $this->salesOrderService->syncOutboundStatus($locked->salesOrder);
            }

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

            $this->auditService->logSemanticSave(
                'dberp.sales_outbound.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(DberpSalesOutboundOrder $order): void
    {
        $totals = $order->items()->selectRaw('COALESCE(SUM(ship_quantity), 0) as total_ship_quantity, COALESCE(SUM(line_amount), 0) as total_amount')->first();

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

    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(),
        );
    }
}
