<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Business\Inventory;

use App\Business\Inventory\Enums\InventoryBusinessType;
use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\Exceptions\InsufficientStockException;
use App\Business\Product\InventoryPostingProductSkuResolver;
use App\Models\DberpInventoryBalance;
use App\Models\DberpOtherStockOutOrder;
use App\Services\DberpAuditService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

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

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

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

                $items = $locked->items()->with('product')->orderBy('sort_order')->orderBy('id')->get();

                if ($items->isEmpty()) {
                    throw ValidationException::withMessages([
                        'items' => __('dberp.errors.inventory_doc_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 ((int) $item->product_id <= 0 || $item->product === null) {
                        throw ValidationException::withMessages([
                            'items' => __('dberp.errors.inventory_outbound_line_incomplete'),
                        ]);
                    }

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

                    $sku = InventoryPostingProductSkuResolver::resolveSkuForPosting(
                        $item->product,
                        $item->product_sku_id !== null ? (int) $item->product_sku_id : null,
                    );

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

                $this->ledgerService->assertNoOutboundShortagesPreflight(
                    $preflightLines,
                    InventoryBusinessType::OtherStockOut,
                    (string) $locked->code,
                );

                foreach ($items as $item) {
                    $sku = InventoryPostingProductSkuResolver::resolveSkuForPosting(
                        $item->product,
                        $item->product_sku_id !== null ? (int) $item->product_sku_id : null,
                    );
                    $applyKey = sprintf('other_stock_out:%d:confirm:%d', (int) $locked->getKey(), (int) $item->getKey());

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

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

                    if (! $post->wasIdempotentReplay) {
                        $result = $this->refinementService->applyOutbound(
                            product: $sku->product,
                            warehouse: $locked->warehouse,
                            quantity: $ledgerQty,
                            businessType: InventoryBusinessType::OtherStockOut,
                            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,
                            ],
                        );

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

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

                $this->auditService->logSemanticSave(
                    'dberp.other_stock_out.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],
                );
            });
        } catch (InsufficientStockException $exception) {
            $this->auditInsufficientStock($exception);

            throw $exception->validationException();
        }
    }

    public function void(DberpOtherStockOutOrder $order): void
    {
        DB::transaction(function () use ($order): void {
            $locked = DberpOtherStockOutOrder::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')->orderBy('sort_order')->orderBy('id')->get();

                foreach ($items as $item) {
                    $sku = InventoryPostingProductSkuResolver::resolveSkuForPosting(
                        $item->product,
                        $item->product_sku_id !== null ? (int) $item->product_sku_id : null,
                    );
                    $voidKey = sprintf('other_stock_out:%d:void:%d', (int) $locked->getKey(), (int) $item->getKey());

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

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

                    if (! $post->wasIdempotentReplay) {
                        $this->refinementService->rollbackOutbound(
                            product: $sku->product,
                            warehouse: $locked->warehouse,
                            quantity: $ledgerQty,
                            businessType: InventoryBusinessType::OtherStockOutVoid,
                            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,
                            ],
                        );
                    }
                }
            }

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

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

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