<?php

namespace App\Http\Controllers\Api;

use App\Core\Http\Controllers\BaseApiController;
use App\Http\Requests\Api\TextAnalysisStoreRequest;
use App\Models\TextAnalysisRequest;
use App\Services\Ai\Exceptions\TextWordLimitExceededException;
use App\Services\Ai\TextAnalysisService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Throwable;

class TextAnalysisController extends BaseApiController
{
    public function __construct(
        private readonly TextAnalysisService $textAnalysis,
    ) {}

    public function limits(Request $request): JsonResponse
    {
        return $this->successResponse('OK', $this->textAnalysis->limitsForUser($request->user()));
    }

    public function store(TextAnalysisStoreRequest $request): JsonResponse
    {
        $data = $request->validated();

        try {
            $result = $this->textAnalysis->analyzeAndHumanize(
                $request->user(),
                $data['text'],
                $data['mode'],
            );
        } catch (TextWordLimitExceededException $e) {
            return $this->errorResponse($e->getMessage(), [
                'code' => 'text_word_limit_exceeded',
                'word_count' => $e->wordCount,
                'max_words' => $e->maxWords,
                'plan_slug' => $e->planSlug,
            ], 422);
        } catch (ValidationException $e) {
            throw $e;
        } catch (Throwable $e) {
            return $this->errorResponse(
                'تعذر تحليل النص. حاول مرة أخرى.',
                ['detail' => config('app.debug') ? $e->getMessage() : null],
                502,
            );
        }

        return $this->successResponse('تم تحليل النص وتحسين الصياغة.', $result);
    }

    public function history(Request $request): JsonResponse
    {
        $rows = TextAnalysisRequest::query()
            ->where('user_id', $request->user()->id)
            ->where('status', TextAnalysisRequest::STATUS_COMPLETED)
            ->orderByDesc('id')
            ->limit(20)
            ->get(['id', 'tone', 'ai_probability_score', 'readability_score', 'created_at']);

        return $this->successResponse('OK', [
            'items' => $rows->map(static fn (TextAnalysisRequest $r) => [
                'id' => $r->id,
                'tone' => $r->tone,
                'ai_probability_score' => $r->ai_probability_score,
                'readability_score' => $r->readability_score,
                'created_at' => $r->created_at?->toIso8601String(),
            ])->all(),
        ]);
    }
}
