<?php

declare(strict_types=1);

namespace Builder\Seo\Support;

use Builder\Seo\Settings\SeoSettings;
use Spatie\SchemaOrg\BaseType;
use Spatie\SchemaOrg\Schema;

/**
 * Builds a Schema.org structured data object from the global SEO settings.
 * Use toScript() to render the JSON-LD <script> tag for the HTML <head>.
 */
final class SchemaOrgBuilder
{
    public function build(SeoSettings $settings): BaseType
    {
        $name = $settings->schema_name ?: $settings->site_name ?: '';

        return match ($settings->schema_type) {
            'Person' => $this->buildPerson($settings, $name),
            'LocalBusiness' => $this->buildLocalBusiness($settings, $name),
            'WebSite' => $this->buildWebSite($settings, $name),
            default => $this->buildOrganization($settings, $name),
        };
    }

    public function toScript(SeoSettings $settings): string
    {
        return $this->build($settings)->toScript();
    }

    private function buildOrganization(SeoSettings $settings, string $name): BaseType
    {
        $schema = Schema::organization()->name($name);

        if (! empty($settings->schema_url)) {
            $schema->url($settings->schema_url);
        }

        if (! empty($settings->schema_logo_url)) {
            $schema->logo($settings->schema_logo_url);
        }

        if (! empty($settings->schema_description)) {
            $schema->description($settings->schema_description);
        }

        return $schema;
    }

    private function buildPerson(SeoSettings $settings, string $name): BaseType
    {
        $schema = Schema::person()->name($name);

        if (! empty($settings->schema_url)) {
            $schema->url($settings->schema_url);
        }

        if (! empty($settings->schema_description)) {
            $schema->description($settings->schema_description);
        }

        return $schema;
    }

    private function buildLocalBusiness(SeoSettings $settings, string $name): BaseType
    {
        $schema = Schema::localBusiness()->name($name);

        if (! empty($settings->schema_url)) {
            $schema->url($settings->schema_url);
        }

        if (! empty($settings->schema_logo_url)) {
            $schema->logo($settings->schema_logo_url);
        }

        if (! empty($settings->schema_description)) {
            $schema->description($settings->schema_description);
        }

        return $schema;
    }

    private function buildWebSite(SeoSettings $settings, string $name): BaseType
    {
        $schema = Schema::webSite()->name($name);

        if (! empty($settings->schema_url)) {
            $schema->url($settings->schema_url);
        }

        if (! empty($settings->schema_description)) {
            $schema->description($settings->schema_description);
        }

        return $schema;
    }
}
