<?php

declare(strict_types=1);

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

namespace App\Support\PageContext;

use App\Filament\Resources\DberpCustomers\Pages\EditDberpCustomer;
use App\Filament\Resources\DberpProducts\Pages\EditDberpProduct;
use App\Filament\Resources\DberpProducts\Pages\ViewDberpProduct;
use App\Filament\Resources\DberpPurchaseOrders\Pages\EditDberpPurchaseOrder;
use App\Filament\Resources\DberpSalesOrders\Pages\EditDberpSalesOrder;
use App\Filament\Resources\DberpSuppliers\Pages\EditDberpSupplier;
use App\Filament\Resources\DberpWarehouses\Pages\EditDberpWarehouse;
use App\Models\DberpCustomer;
use App\Models\DberpPayableRecord;
use App\Models\DberpProduct;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpReceivableRecord;
use App\Models\DberpSalesOrder;
use App\Models\DberpSupplier;
use App\Models\DberpWarehouse;
use App\Tools\Context\ErpPageContext;
use App\Tools\Context\PageContextSource;
use App\Tools\Context\PageKind;
use App\Tools\Entity\EntityReference;
use App\Tools\Entity\EntityType;
use Illuminate\Database\Eloquent\Model;
use Throwable;

/**
 * 在受信任的 Filament 记录页把已持久化档案转成 ErpPageContext。
 * 必须重新查询数据库，禁止使用未保存表单或 Livewire 脏属性。
 */
final class FilamentPageContextCapture
{
    /**
     * 仅从已批准的 Filament 记录页采集上下文。列表、创建、选中行与未映射页面返回 null。
     */
    public function fromCurrentLivewirePage(mixed $page): ?ErpPageContext
    {
        if (! is_object($page)) {
            return null;
        }

        $pageKind = $this->pageKindFor($page);

        if (! $pageKind instanceof PageKind || ! method_exists($page, 'getRecord')) {
            return null;
        }

        try {
            $record = $page->getRecord();
        } catch (Throwable) {
            return null;
        }

        return $this->fromPersistedRecord($record, $pageKind);
    }

    public function fromPersistedRecord(mixed $record, PageKind $pageKind): ?ErpPageContext
    {
        if (! $record instanceof Model) {
            return null;
        }

        $type = $pageKind->entityType();
        $modelClass = $this->modelClass($type);

        if ($modelClass === null || ! $record instanceof $modelClass) {
            return null;
        }

        $id = $record->getKey();

        if (! is_numeric($id) || (int) $id <= 0) {
            return null;
        }

        $persisted = $this->reload($modelClass, (int) $id);

        if (! $persisted instanceof Model) {
            return null;
        }

        $reference = EntityReference::tryMake(
            $type,
            $persisted->getKey(),
            $this->stringAttribute($persisted, 'code'),
            $this->stringAttribute($persisted, 'name'),
        );

        if (! $reference instanceof EntityReference) {
            return null;
        }

        return new ErpPageContext(
            $pageKind,
            $reference,
            PageContextSource::FilamentResourceRecord,
        );
    }

    /**
     * @param  class-string<Model>  $modelClass
     */
    private function reload(string $modelClass, int $id): ?Model
    {
        try {
            $record = $modelClass::query()->whereKey($id)->first();
        } catch (Throwable) {
            return null;
        }

        return $record instanceof Model ? $record : null;
    }

    private function stringAttribute(Model $record, string $attribute): ?string
    {
        $value = $record->getAttribute($attribute);

        if (! is_string($value) && ! is_numeric($value)) {
            return null;
        }

        $normalized = trim((string) $value);

        return $normalized === '' ? null : $normalized;
    }

    private function pageKindFor(object $page): ?PageKind
    {
        return match ($page::class) {
            ViewDberpProduct::class => PageKind::ProductView,
            EditDberpProduct::class => PageKind::ProductEdit,
            EditDberpCustomer::class => PageKind::CustomerEdit,
            EditDberpSupplier::class => PageKind::SupplierEdit,
            EditDberpWarehouse::class => PageKind::WarehouseEdit,
            EditDberpSalesOrder::class => PageKind::SalesOrderEdit,
            EditDberpPurchaseOrder::class => PageKind::PurchaseOrderEdit,
            default => null,
        };
    }

    /**
     * @return class-string<Model>|null
     */
    private function modelClass(EntityType $type): ?string
    {
        return match ($type) {
            EntityType::Product => DberpProduct::class,
            EntityType::Customer => DberpCustomer::class,
            EntityType::Supplier => DberpSupplier::class,
            EntityType::Warehouse => DberpWarehouse::class,
            EntityType::SalesOrder => DberpSalesOrder::class,
            EntityType::PurchaseOrder => DberpPurchaseOrder::class,
            EntityType::Receivable => DberpReceivableRecord::class,
            EntityType::Payable => DberpPayableRecord::class,
        };
    }
}
