<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Artwork;
use App\Services\Enhance\EnhanceService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use RuntimeException;

final class ArtworkEnhanceController extends Controller
{
    public function __construct(
        private readonly EnhanceService $enhanceService,
    ) {
    }

    public function store(Request $request, int $artwork): RedirectResponse
    {
        $artwork = Artwork::query()->findOrFail($artwork);

        $actor = $request->user();
        abort_unless($actor !== null, 403);

        $isOwner = (int) $artwork->user_id === (int) $actor->id;
        $isStaff = $actor->isAdmin() || $actor->isModerator();

        abort_unless($isOwner || $isStaff, 403);

        $validated = $request->validate([
            'scale' => ['required', 'integer', Rule::in((array) config('enhance.allowed_scales', [2, 4]))],
            'mode' => ['required', 'string', Rule::in((array) config('enhance.allowed_modes', ['standard', 'artwork', 'photo', 'illustration']))],
        ]);

        try {
            $job = $this->enhanceService->createFromArtwork($actor, $artwork, $validated);
        } catch (RuntimeException $exception) {
            return redirect()
                ->route('enhance.create', ['artwork' => $artwork->id])
                ->withErrors([
                    'source' => $exception->getMessage(),
                ]);
        }

        return redirect()
            ->route('enhance.show', ['enhanceJob' => $job])
            ->with('success', 'Artwork enhance job created.');
    }
}