<?php

namespace App\Http\Controllers;

use App\Enums\SpecDocumentSectionType;
use App\Http\Requests\SpecDocumentRequest;
use App\Http\Requests\UpdateSpecDocumentSectionTemplate;
use App\Models\SpecDocumentSectionTemplate;
use App\SpecDocumentBlueprint;
use Illuminate\Support\Facades\Auth;

/**
 * System-level management of spec document section templates (central connection). A
 * template holds the default field data for a templatable section type; new documents
 * auto-fill those sections from the template and can then be adjusted per instance.
 */
class SpecDocumentSectionTemplateController extends Controller
{
    public function index(SpecDocumentRequest $request, SpecDocumentBlueprint $blueprint): array
    {
        $stored = SpecDocumentSectionTemplate::query()->get()->keyBy('type');

        return [
            'templates' => collect($blueprint->templatableTypes())
                ->map(fn (SpecDocumentSectionType $type) => [
                    'type' => $type->value,
                    'label' => $type->label(),
                    'fields' => $blueprint->fields($type),
                    'data' => $stored->get($type->value)?->data,
                ])
                ->values(),
        ];
    }

    public function update(
        UpdateSpecDocumentSectionTemplate $request,
        SpecDocumentBlueprint $blueprint,
        string $type
    ): array {
        abort_unless($blueprint->isTemplatable($type), 404);

        // Tenant-linked fields are per-site and must not carry a template default.
        $data = collect($request->input('data', []))
            ->except(array_keys($blueprint->tenantFields($type)))
            ->all();

        SpecDocumentSectionTemplate::query()->updateOrCreate(
            ['type' => $type],
            ['data' => $data, 'updated_by' => Auth::id()],
        );

        return $this->index($request, $blueprint);
    }
}
