<?php

namespace App\Extensions\Installed\Importer\Services;

use App\Extensions\Installed\Importer\Models\ImportJob;
use App\Extensions\Installed\Importer\Services\ApiAdapters\{
    ApiAdapterRegistry,
    ApiImportAdapter,
};

class ApiImporter extends DatabaseImporter
{
    protected function bootAdapter(): void
    {
        $options = $this->job->options ?? [];
        $system = $options["api_system"] ?? "freshdesk";

        try {
            $adapter = ApiAdapterRegistry::resolve($system);
            $adapter->boot($this->job->db_config ?? [], $options);
        } catch (\Throwable $e) {
            throw new \RuntimeException(
                "Could not initialise API adapter: {$e->getMessage()}",
                0,
                $e,
            );
        }

        $this->adapter = $adapter;
    }

    public static function createJob(
        array $apiConfig,
        array $options = [],
        ?string $name = null,
    ): ImportJob {
        $defaultChunk = config("extensions.importer.chunk_size", 100) ?? 100;

        $system = $options["api_system"] ?? "freshdesk";
        $adapterClass = ApiAdapterRegistry::adapterClass($system);

        if (!$adapterClass) {
            throw new \InvalidArgumentException(
                "Unknown API import adapter [{$system}].",
            );
        }
        if ($adapterClass::isPreview()) {
            throw new \RuntimeException(
                sprintf(
                    "%s API import is not available yet.",
                    $adapterClass::label(),
                ),
            );
        }

        $adapterDefaults = $adapterClass::defaults();

        $jobOptions = array_merge(
            [
                "import_departments" => true,
                "import_categories" => false,
                "import_users" => true,
                "import_operators" => true,
                "import_tickets" => true,
                "import_responses" => false,
                "import_articles" => false,
                "default_password" => "changeme123",
                "force_password_reset" => true,
                "dry_run" => false,
            ],
            $adapterDefaults["options"] ?? [],
            $options,
        );

        $jobOptions["api_system"] = $system;

        $systemLabel = $adapterClass::label();
        $chunkSize =
            $options["chunk_size"] ??
            ($adapterDefaults["chunk_size"] ?? null ?? $defaultChunk);

        return ImportJob::create([
            "name" => $name ?? sprintf("%s API Import", $systemLabel),
            "source" => $system,
            "type" => "database",
            "status" => "pending",
            "total_rows" => 0,
            "processed_rows" => 0,
            "failed_rows" => 0,
            "current_offset" => 0,
            "chunk_size" => $chunkSize,
            "db_config" => $apiConfig,
            "options" => $jobOptions,
            "errors" => [],
        ]);
    }
}
