<?php

declare(strict_types=1);

namespace App\Http\Controllers\Studio;

use App\Http\Controllers\Controller;
use App\Http\Requests\Groups\StoreGroupEventRequest;
use App\Http\Requests\Groups\UpdateGroupEventRequest;
use App\Models\Group;
use App\Models\GroupEvent;
use App\Services\GroupEventService;
use App\Services\GroupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

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

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

        return Inertia::render('Studio/StudioGroupEvents', [
            'title' => $group->name . ' Events',
            'description' => 'Manage launches, milestones, streams, and timeline-aware group moments.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'listing' => $this->events->studioListing($group, $request->only(['bucket', 'page', 'per_page'])),
            'recentHistory' => $this->groups->recentHistory($group),
            'createUrl' => route('studio.groups.events.create', ['group' => $group]),
        ]);
    }

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

        return Inertia::render('Studio/StudioGroupEventEditor', [
            'title' => 'Create event',
            'description' => 'Schedule a release, internal session, livestream, or other group event.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'event' => null,
            'typeOptions' => collect((array) config('groups.events.types', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucwords(str_replace('_', ' ', $value))])->values()->all(),
            'statusOptions' => collect((array) config('groups.events.statuses', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucfirst($value)])->values()->all(),
            'visibilityOptions' => collect((array) config('groups.events.visibility_options', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucwords(str_replace('_', ' ', $value))])->values()->all(),
            'projectOptions' => $group->projects()->orderBy('title')->get(['id', 'title'])->map(fn ($project): array => ['id' => (int) $project->id, 'title' => $project->title])->values()->all(),
            'challengeOptions' => $group->challenges()->orderBy('title')->get(['id', 'title'])->map(fn ($challenge): array => ['id' => (int) $challenge->id, 'title' => $challenge->title])->values()->all(),
            'collectionOptions' => $group->collections()->orderBy('title')->get(['id', 'title'])->map(fn ($collection): array => ['id' => (int) $collection->id, 'title' => $collection->title])->values()->all(),
            'storeUrl' => route('studio.groups.events.store', ['group' => $group]),
        ]);
    }

    public function store(StoreGroupEventRequest $request, Group $group): RedirectResponse
    {
        $this->authorize('manageEvents', $group);

        $event = $this->events->create($group, $request->user(), $request->validated());

        return redirect()->route('studio.groups.events.edit', ['group' => $group, 'event' => $event])
            ->with('success', 'Event created.');
    }

    public function edit(Request $request, Group $group, GroupEvent $event): Response
    {
        abort_unless($group->canManageEvents($request->user()) || $group->canPublishEventUpdates($request->user()), 403);
        abort_unless((int) $event->group_id === (int) $group->id, 404);

        return Inertia::render('Studio/StudioGroupEventEditor', [
            'title' => 'Edit event',
            'description' => 'Refine public details and publish event updates safely.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'event' => $this->events->detailPayload($event),
            'typeOptions' => collect((array) config('groups.events.types', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucwords(str_replace('_', ' ', $value))])->values()->all(),
            'statusOptions' => collect((array) config('groups.events.statuses', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucfirst($value)])->values()->all(),
            'visibilityOptions' => collect((array) config('groups.events.visibility_options', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucwords(str_replace('_', ' ', $value))])->values()->all(),
            'projectOptions' => $group->projects()->orderBy('title')->get(['id', 'title'])->map(fn ($project): array => ['id' => (int) $project->id, 'title' => $project->title])->values()->all(),
            'challengeOptions' => $group->challenges()->orderBy('title')->get(['id', 'title'])->map(fn ($challenge): array => ['id' => (int) $challenge->id, 'title' => $challenge->title])->values()->all(),
            'collectionOptions' => $group->collections()->orderBy('title')->get(['id', 'title'])->map(fn ($collection): array => ['id' => (int) $collection->id, 'title' => $collection->title])->values()->all(),
            'updateUrl' => route('studio.groups.events.update', ['group' => $group, 'event' => $event]),
            'publishUrl' => route('studio.groups.events.publish', ['group' => $group, 'event' => $event]),
        ]);
    }

    public function update(UpdateGroupEventRequest $request, Group $group, GroupEvent $event): RedirectResponse
    {
        abort_unless($group->canManageEvents($request->user()) || $group->canPublishEventUpdates($request->user()), 403);
        abort_unless((int) $event->group_id === (int) $group->id, 404);

        $this->events->update($event, $request->user(), $request->validated());

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

    public function publish(Request $request, Group $group, GroupEvent $event): RedirectResponse
    {
        $this->authorize('manageEvents', $group);
        abort_unless((int) $event->group_id === (int) $group->id, 404);

        $this->events->publish($event, $request->user());

        return back()->with('success', 'Event published.');
    }
}