<?php

declare(strict_types=1);

namespace App\Http\Controllers\Studio;

use App\Http\Controllers\Controller;
use App\Http\Requests\Studio\ApplyArtworkAiAssistRequest;
use App\Services\Studio\StudioAiAssistEventService;
use App\Services\Studio\StudioAiAssistService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class StudioArtworkAiAssistApiController extends Controller
{
    public function __construct(
        private readonly StudioAiAssistService $aiAssist,
        private readonly StudioAiAssistEventService $eventService,
    ) {
    }

    public function show(Request $request, int $id): JsonResponse
    {
        $artwork = $request->user()->artworks()->with(['tags', 'categories.contentType', 'artworkAiAssist'])->findOrFail($id);

        return response()->json([
            'data' => $this->aiAssist->payloadFor($artwork),
        ]);
    }

    public function analyze(Request $request, int $id): JsonResponse
    {
        $artwork = $request->user()->artworks()->with(['tags', 'categories.contentType'])->findOrFail($id);
        $direct = (bool) $request->boolean('direct');
        $intent = $request->validate([
            'direct' => ['sometimes', 'boolean'],
            'intent' => ['sometimes', 'nullable', 'string', 'in:analyze,title,description,tags,category,similar'],
        ])['intent'] ?? null;

        if ($direct) {
            $assist = $this->aiAssist->analyzeDirect($artwork, false, $intent);

            return response()->json([
                'success' => true,
                'status' => $assist->status,
                'direct' => true,
                'data' => $this->aiAssist->payloadFor($artwork->fresh(['tags', 'categories.contentType', 'artworkAiAssist'])),
            ]);
        }

        $assist = $this->aiAssist->queueAnalysis($artwork, false, $intent);

        return response()->json([
            'success' => true,
            'status' => $assist->status,
            'direct' => false,
        ], 202);
    }

    public function regenerate(Request $request, int $id): JsonResponse
    {
        $artwork = $request->user()->artworks()->with(['tags', 'categories.contentType'])->findOrFail($id);
        $direct = (bool) $request->boolean('direct');
        $intent = $request->validate([
            'direct' => ['sometimes', 'boolean'],
            'intent' => ['sometimes', 'nullable', 'string', 'in:analyze,title,description,tags,category,similar'],
        ])['intent'] ?? null;

        if ($direct) {
            $assist = $this->aiAssist->analyzeDirect($artwork, true, $intent);

            return response()->json([
                'success' => true,
                'status' => $assist->status,
                'direct' => true,
                'data' => $this->aiAssist->payloadFor($artwork->fresh(['tags', 'categories.contentType', 'artworkAiAssist'])),
            ]);
        }

        $assist = $this->aiAssist->queueAnalysis($artwork, true, $intent);

        return response()->json([
            'success' => true,
            'status' => $assist->status,
            'direct' => false,
        ], 202);
    }

    public function apply(ApplyArtworkAiAssistRequest $request, int $id): JsonResponse
    {
        $artwork = $request->user()->artworks()->with(['tags', 'categories.contentType', 'artworkAiAssist'])->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $this->aiAssist->applySuggestions($artwork, $request->validated()),
        ]);
    }

    public function event(Request $request, int $id): JsonResponse
    {
        $payload = $request->validate([
            'event_type' => ['required', 'string', 'max:64'],
            'meta' => ['sometimes', 'array'],
        ]);

        $artwork = $request->user()->artworks()->with('artworkAiAssist')->findOrFail($id);

        $this->eventService->record(
            $artwork,
            (string) $payload['event_type'],
            (array) ($payload['meta'] ?? []),
            $artwork->artworkAiAssist,
        );

        return response()->json(['success' => true], 201);
    }
}