<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Artwork;
use App\Models\Collection;
use App\Models\CollectionSubmission;
use App\Services\CollectionSubmissionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CollectionSubmissionController extends Controller
{
    public function __construct(
        private readonly CollectionSubmissionService $submissions,
    ) {
    }

    public function store(Request $request, Collection $collection): JsonResponse
    {
        $this->authorize('submit', $collection);

        $data = $request->validate([
            'artwork_id' => ['required', 'integer', 'min:1'],
            'message' => ['nullable', 'string', 'max:1000'],
        ]);

        $artwork = Artwork::query()->findOrFail((int) $data['artwork_id']);
        $submission = $this->submissions->submit($collection, $request->user(), $artwork, $data['message'] ?? null);

        return response()->json([
            'ok' => true,
            'submission' => $submission,
            'submissions' => $this->submissions->mapSubmissions($collection, $request->user()),
        ]);
    }

    public function approve(Request $request, CollectionSubmission $submission): JsonResponse
    {
        $submission = $this->submissions->approve($submission, $request->user());

        return response()->json([
            'ok' => true,
            'submissions' => $this->submissions->mapSubmissions($submission->collection, $request->user()),
        ]);
    }

    public function reject(Request $request, CollectionSubmission $submission): JsonResponse
    {
        $submission = $this->submissions->reject($submission, $request->user());

        return response()->json([
            'ok' => true,
            'submissions' => $this->submissions->mapSubmissions($submission->collection, $request->user()),
        ]);
    }

    public function destroy(Request $request, CollectionSubmission $submission): JsonResponse
    {
        $collection = $submission->collection;
        $this->submissions->withdraw($submission, $request->user());

        return response()->json([
            'ok' => true,
            'submissions' => $this->submissions->mapSubmissions($collection, $request->user()),
        ]);
    }
}
