<?php

declare(strict_types=1);

namespace App\Http\Controllers\Internal;

use App\Http\Controllers\Controller;
use App\Models\NovaCard;
use App\Services\NovaCards\NovaCardPresenter;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class NovaCardRenderFrameController extends Controller
{
    public function __construct(
        private readonly NovaCardPresenter $presenter,
    ) {
    }

    public function show(Request $request, string $uuid): Response
    {
        abort_unless($request->hasValidSignature(), 403);

        $card = NovaCard::query()
            ->with(['backgroundImage', 'user'])
            ->where('uuid', $uuid)
            ->firstOrFail();

        $format = config('nova_cards.formats.' . $card->format) ?? config('nova_cards.formats.square');
        $width  = (int) ($format['width']  ?? 1080);
        $height = (int) ($format['height'] ?? 1080);

        $cardData = $this->presenter->card($card, true, $card->user);

        $fonts = collect((array) config('nova_cards.font_presets', []))
            ->map(fn (array $v, string $k): array => array_merge($v, ['key' => $k]))
            ->values()
            ->all();

        return response()->view('nova-cards.render-frame', compact('cardData', 'fonts', 'width', 'height'));
    }
}
