<?php

declare(strict_types=1);

namespace App\Http\Controllers\Studio;

use App\Http\Controllers\Controller;
use App\Http\Requests\Groups\PinGroupActivityItemRequest;
use App\Models\Group;
use App\Models\GroupActivityItem;
use App\Services\GroupActivityService;
use App\Services\GroupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class GroupActivityStudioController extends Controller
{
    public function __construct(
        private readonly GroupService $groups,
        private readonly GroupActivityService $activity,
    ) {
    }

    public function index(Request $request, Group $group): Response
    {
        $this->authorize('viewStudio', $group);

        return Inertia::render('Studio/StudioGroupActivity', [
            'title' => $group->name . ' Activity',
            'description' => 'Track public and internal group events from one activity timeline.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'activity' => $this->activity->studioFeed($group, $request->user(), 30),
            'pinPattern' => $group->canPinActivity($request->user()) ? route('studio.groups.activity.pin', ['group' => $group, 'item' => '__ITEM__']) : null,
        ]);
    }

    public function pin(PinGroupActivityItemRequest $request, Group $group, GroupActivityItem $item): RedirectResponse
    {
        $this->authorize('pinActivity', $group);
        abort_unless((int) $item->group_id === (int) $group->id, 404);

        $this->activity->pin($item, $request->user(), (bool) $request->boolean('is_pinned', ! $item->is_pinned));

        return back()->with('success', 'Activity updated.');
    }
}