<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Group;
use App\Models\GroupEvent;
use App\Services\GroupEventService;
use App\Services\GroupService;
use App\Support\Seo\SeoFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class GroupEventController extends Controller
{
    public function __construct(
        private readonly GroupService $groups,
        private readonly GroupEventService $events,
    ) {
    }

    public function show(Request $request, Group $group, GroupEvent $event): Response
    {
        $this->authorize('view', $group);
        abort_unless((int) $event->group_id === (int) $group->id, 404);
        abort_unless($event->canBeViewedBy($request->user()), 403);

        $groupPayload = $this->groups->mapGroupDetail($group, $request->user());
        $eventPayload = $this->events->detailPayload($event);
        $canonical = route('groups.events.show', ['group' => $group, 'event' => $event]);
        $description = Str::limit(trim(strip_tags((string) ($eventPayload['summary'] ?? $eventPayload['description'] ?? $groupPayload['headline'] ?? 'Group event on Skinbase.'))), 160, '…');
        $seo = app(SeoFactory::class)->collectionPage(
            sprintf('%s — %s — Skinbase', $event->title, $group->name),
            $description,
            $canonical,
            $eventPayload['cover_url'] ?? null,
        )->toArray();
        $seo['og_type'] = 'article';
        $seo['json_ld'] = [[
            '@context' => 'https://schema.org',
            '@type' => 'Event',
            'name' => (string) $event->title,
            'description' => $description,
            'url' => $canonical,
            'image' => $eventPayload['cover_url'] ?? null,
            'startDate' => $event->start_at?->toAtomString(),
            'endDate' => $event->end_at?->toAtomString(),
            'eventAttendanceMode' => 'https://schema.org/OnlineEventAttendanceMode',
            'eventStatus' => 'https://schema.org/EventScheduled',
            'organizer' => ['@type' => 'Organization', 'name' => (string) $group->name],
        ]];

        return Inertia::render('Group/GroupEventShow', [
            'group' => $groupPayload,
            'event' => $eventPayload,
            'seo' => $seo,
        ])->rootView('collections');
    }
}