<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\OpenAIService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class OpenAIController extends Controller
{
    private OpenAIService $openAIService;

    public function __construct(OpenAIService $openAIService)
    {
        $this->openAIService = $openAIService;
    }

    /**
     * Handle OpenAI requests for testing
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'input' => ['required', 'string'],
            'model' => ['sometimes', 'string'],
            'instructions' => ['sometimes', 'string'],
            'temperature' => ['sometimes', 'numeric', 'min:0', 'max:2'],
            'max_output_tokens' => ['sometimes', 'integer', 'min:1'],
            'top_p' => ['sometimes', 'numeric', 'min:0', 'max:1'],
        ]);

        $params = [
            'input' => $validated['input'],
            'model' => $validated['model'] ?? null,
            'instructions' => $validated['instructions'] ?? null,
            'temperature' => $validated['temperature'] ?? null,
            'max_output_tokens' => $validated['max_output_tokens'] ?? null,
            'top_p' => $validated['top_p'] ?? null,
        ];

        // Remove null values to use defaults from service
        $params = array_filter($params, fn ($value) => $value !== null);

        try {
            $data = $this->openAIService->createResponse($params);

            return response()->json([
                'status' => 'success',
                'data' => $data,
            ]);
        } catch (\RuntimeException $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
