<?php

declare(strict_types=1);

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

namespace App\Business\DataImport;

use App\Business\DataImport\Contracts\DataImportHandler;
use App\Business\DataImport\Enums\DataImportType;
use Illuminate\Contracts\Container\Container;
use InvalidArgumentException;

final class DataImportDefinitionRegistry
{
    /**
     * @var array<string, DataImportTypeDefinition>
     */
    private array $definitions = [];

    public function __construct(
        private readonly Container $container,
    ) {}

    public function register(DataImportTypeDefinition $definition): void
    {
        $this->assertValidDefinition($definition);

        if (isset($this->definitions[$definition->key])) {
            throw DataImportDefinitionConflictException::duplicateKey($definition->key);
        }

        if (! $definition->builtin && DataImportType::tryFrom($definition->key) !== null) {
            throw DataImportDefinitionConflictException::builtinOverride($definition->key);
        }

        $this->definitions[$definition->key] = $definition;
    }

    public function has(string $key): bool
    {
        return isset($this->definitions[$key]);
    }

    public function get(string $key): DataImportTypeDefinition
    {
        return $this->definitions[$key]
            ?? throw new InvalidArgumentException(sprintf('Data import type [%s] is not registered.', $key));
    }

    public function tryGet(string $key): ?DataImportTypeDefinition
    {
        return $this->definitions[$key] ?? null;
    }

    /**
     * @return class-string<DataImportHandler>
     */
    public function handlerClass(string $key): string
    {
        return $this->get($key)->handlerClass;
    }

    public function resolveHandler(string $key): DataImportHandler
    {
        $handlerClass = $this->handlerClass($key);

        return $this->container->make($handlerClass);
    }

    /**
     * @return list<string>
     */
    public function keys(): array
    {
        return array_keys($this->definitions);
    }

    /**
     * @return list<DataImportTypeDefinition>
     */
    public function all(): array
    {
        return array_values($this->definitions);
    }

    /**
     * @return list<DataImportTypeDefinition>
     */
    public function extensions(): array
    {
        return array_values(array_filter(
            $this->definitions,
            static fn (DataImportTypeDefinition $definition): bool => ! $definition->builtin,
        ));
    }

    /**
     * @return list<DataImportType>
     */
    public function builtinEnumTypes(): array
    {
        $types = [];

        foreach ($this->definitions as $definition) {
            if (! $definition->builtin) {
                continue;
            }

            $enum = DataImportType::tryFrom($definition->key);

            if ($enum !== null) {
                $types[] = $enum;
            }
        }

        return $types;
    }

    private function assertValidDefinition(DataImportTypeDefinition $definition): void
    {
        $key = trim($definition->key);

        if ($key === '' || ! preg_match('/^[a-z][a-z0-9_]*$/', $key)) {
            throw new InvalidArgumentException(sprintf('Invalid data import type key [%s].', $definition->key));
        }

        if (trim($definition->label) === '') {
            throw new InvalidArgumentException(sprintf('Data import type [%s] requires a display label.', $definition->key));
        }

        if (! is_subclass_of($definition->handlerClass, DataImportHandler::class)) {
            throw new InvalidArgumentException(sprintf(
                'Handler [%s] for import type [%s] must implement %s.',
                $definition->handlerClass,
                $definition->key,
                DataImportHandler::class,
            ));
        }
    }
}
