<?php

namespace App\Http\Controllers\Api;

use App\Core\Http\Controllers\BaseApiController;
use App\Models\UserAiMemory;
use App\Services\Subscriptions\AiQuotaService;
use App\Services\Subscriptions\PlanCapabilities;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * AI Studio — ذاكرة ذكية (تفضيلات المستخدم لتحسين الردود لاحقاً).
 */
class AiMemoryController extends BaseApiController
{
    public function __construct(
        private readonly AiQuotaService $quota,
    ) {}

    public function show(Request $request): JsonResponse
    {
        if ($deny = $this->memoryDenied($request)) {
            return $deny;
        }
        $user = $request->user();
        $m = UserAiMemory::query()->firstOrCreate(
            ['user_id' => $user->id],
            ['interests' => null, 'style_notes' => null, 'recent_topics' => null, 'extra' => []],
        );

        return $this->successResponse('OK', [
            'memory' => [
                'interests' => $m->interests,
                'style_notes' => $m->style_notes,
                'recent_topics' => $m->recent_topics,
                'extra' => $m->extra,
                'updated_at' => $m->updated_at?->toIso8601String(),
            ],
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        if ($deny = $this->memoryDenied($request)) {
            return $deny;
        }
        $user = $request->user();
        $data = $request->validate([
            'interests' => ['nullable', 'string', 'max:5000'],
            'style_notes' => ['nullable', 'string', 'max:5000'],
            'recent_topics' => ['nullable', 'string', 'max:5000'],
        ]);

        $m = UserAiMemory::query()->firstOrCreate(['user_id' => $user->id], []);
        $payload = [];
        foreach (['interests', 'style_notes', 'recent_topics'] as $k) {
            if (array_key_exists($k, $data)) {
                $payload[$k] = $data[$k];
            }
        }
        $m->fill($payload);
        $m->save();

        return $this->successResponse('تم تحديث الذاكرة', [
            'memory' => [
                'interests' => $m->interests,
                'style_notes' => $m->style_notes,
                'recent_topics' => $m->recent_topics,
            ],
        ]);
    }

    private function memoryDenied(Request $request): ?JsonResponse
    {
        $user = $request->user();
        $plan = $this->quota->resolveEffectivePlan($user);
        if (empty(PlanCapabilities::forPlan($plan)['memory_ai'])) {
            return $this->errorResponse('الذاكرة الذكية متاحة لخطط Ultra.', ['code' => 'memory_ai_locked'], 403);
        }

        return null;
    }
}
