<?php

declare(strict_types=1);

namespace App\Http\Controllers;

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

class GroupReleaseController extends Controller
{
    public function __construct(
        private readonly GroupService $groups,
        private readonly GroupReleaseService $releases,
    ) {
    }

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

        $groupPayload = $this->groups->mapGroupDetail($group, $request->user());
        $releasePayload = $this->releases->detailPayload($release, $request->user());
        $canonical = route('groups.releases.show', ['group' => $group, 'release' => $release]);
        $description = Str::limit(trim(strip_tags((string) ($releasePayload['summary'] ?? $releasePayload['description'] ?? $groupPayload['headline'] ?? 'Group release on Skinbase.'))), 160, '…');
        $seo = app(SeoFactory::class)->collectionPage(
            sprintf('%s — %s — Skinbase', $release->title, $group->name),
            $description,
            $canonical,
            $releasePayload['cover_url'] ?? null,
        )->toArray();
        $seo['og_type'] = 'article';
        $seo['json_ld'] = [[
            '@context' => 'https://schema.org',
            '@type' => 'CreativeWork',
            'name' => (string) $release->title,
            'description' => $description,
            'url' => $canonical,
            'image' => $releasePayload['cover_url'] ?? null,
            'datePublished' => $release->published_at?->toAtomString(),
            'dateCreated' => $release->created_at?->toAtomString(),
            'publisher' => ['@type' => 'Organization', 'name' => (string) $group->name],
        ]];

        return Inertia::render('Group/GroupReleaseShow', [
            'group' => $groupPayload,
            'release' => $releasePayload,
            'seo' => $seo,
        ])->rootView('collections');
    }
}