<?php

namespace App\Services;

use App\Models\Macro;
use App\Models\Setting;

class NameTagSlideBuilder
{
    public function buildModeratorSlide(string $name): ?array
    {
        return $this->build($name, 'Moderation');
    }

    public function buildPreacherSlide(string $name): ?array
    {
        return $this->build($name, 'Predigt');
    }

    public function build(string $name, string $title): ?array
    {
        $macroId = Setting::get('namenseinblender_macro_id');

        if ($macroId !== null && trim($macroId) !== '') {
            $macro = Macro::with('collections')->find((int) $macroId);

            if ($macro !== null) {
                $collection = $macro->collections->first();

                return $this->withSubtitle([
                    'text' => $name,
                    'macro' => [
                        'name' => $macro->name,
                        'uuid' => $macro->uuid,
                        'collectionName' => $collection?->name ?? '--MAIN--',
                        'collectionUuid' => $collection?->uuid ?? null,
                    ],
                ], $title);
            }

            // macro_id is configured but the Macro record is missing — still return a slide
            // without a macro so the name tag is not silently dropped.
            return $this->withSubtitle(['text' => $name], $title);
        }

        $macroName = Setting::get('namenseinblender_macro_name');

        if ($macroName === null || trim($macroName) === '') {
            return null;
        }

        return $this->withSubtitle([
            'text' => $name,
            'macro' => [
                'name' => $macroName,
                'uuid' => Setting::get('namenseinblender_macro_uuid'),
                'collectionName' => Setting::get('namenseinblender_macro_collection_name', '--MAIN--'),
                'collectionUuid' => Setting::get('namenseinblender_macro_collection_uuid'),
            ],
        ], $title);
    }

    /**
     * Add the role line as a separate `subtitle` key so the generator can render
     * it smaller and non-bold. Only set when the title is non-empty.
     *
     * @param  array<string, mixed>  $slideData
     * @return array<string, mixed>
     */
    private function withSubtitle(array $slideData, string $title): array
    {
        if (trim($title) !== '') {
            $slideData['subtitle'] = $title;
        }

        return $slideData;
    }
}
