<?php

declare(strict_types=1);

namespace App\Http\Controllers\Academy;

use App\Http\Controllers\Controller;
use App\Http\Requests\Academy\StoreAcademyChallengeSubmissionRequest;
use App\Models\AcademyChallenge;
use App\Models\Artwork;
use App\Services\Academy\AcademyAccessService;
use App\Services\Academy\AcademyChallengeService;
use App\Support\Seo\SeoFactory;
use Inertia\Inertia;
use Inertia\Response;
use Illuminate\Http\RedirectResponse;

final class AcademyChallengeSubmissionController extends Controller
{
    public function __construct(
        private readonly AcademyAccessService $access,
        private readonly AcademyChallengeService $challenges,
    ) {
    }

    public function create(string $slug): Response
    {
        abort_unless((bool) config('academy.enabled', true), 404);
        abort_unless((bool) config('academy.challenges_enabled', true), 404);

        $challenge = AcademyChallenge::query()->where('slug', $slug)->firstOrFail();
        abort_unless($this->access->canAccessChallenge(request()->user(), $challenge), 403);

        $seo = app(SeoFactory::class)->collectionPage(
            'Submit to ' . $challenge->title . ' — Skinbase Academy',
            'Attach one of your artworks to this Academy challenge submission.',
            route('academy.challenges.submit', ['slug' => $challenge->slug]),
        )->toArray();

        return Inertia::render('Academy/ChallengeSubmit', [
            'seo' => $seo,
            'challenge' => $this->access->challengePayload($challenge, request()->user(), true),
            'artworks' => $this->challenges->eligibleArtworkOptions(request()->user())->map(fn (Artwork $artwork): array => [
                'id' => (int) $artwork->id,
                'title' => (string) ($artwork->title ?? 'Untitled artwork'),
                'thumb_url' => $artwork->thumbUrl('md'),
                'published_at' => $artwork->published_at?->toISOString(),
            ])->values()->all(),
            'submitUrl' => route('academy.challenges.submit.store', ['slug' => $challenge->slug]),
        ])->rootView('collections');
    }

    public function store(StoreAcademyChallengeSubmissionRequest $request, string $slug): RedirectResponse
    {
        abort_unless((bool) config('academy.enabled', true), 404);
        abort_unless((bool) config('academy.challenges_enabled', true), 404);

        $challenge = AcademyChallenge::query()->where('slug', $slug)->firstOrFail();
        $artwork = Artwork::query()->findOrFail((int) $request->validated('artwork_id'));

        $this->challenges->submit($request->user(), $challenge, $artwork, $request->validated());

        return redirect()->route('academy.challenges.show', ['slug' => $challenge->slug])
            ->with('success', 'Challenge submission received and queued for review.');
    }
}