<?php

namespace App\Services\Subscriptions;

use App\Models\FileUpload;
use App\Models\ImageGeneration;
use App\Models\TextAnalysisRequest;
use App\Models\SubscriptionPlan;
use App\Modules\Users\Models\User;
use Illuminate\Validation\ValidationException;

/**
 * حدود استخدام أدوات AI Studio اليومية حسب الخطة.
 */
final class StudioQuotaService
{
    public function __construct(
        private readonly AiQuotaService $quota,
    ) {}

    public function isEnabled(SubscriptionPlan $plan, string $feature): bool
    {
        $caps = PlanCapabilities::forPlan($plan);

        return ! empty($caps[$feature]);
    }

    public function dailyLimit(SubscriptionPlan $plan, string $feature): ?int
    {
        $caps = PlanCapabilities::forPlan($plan);
        $key = $feature.'_daily_limit';
        if (! array_key_exists($key, $caps)) {
            return null;
        }
        $raw = $caps[$key];
        if ($raw === null || $raw === '') {
            return null;
        }
        $n = (int) $raw;

        return $n > 0 ? $n : null;
    }

    public function todayUsage(User $user, string $feature): int
    {
        $today = now()->toDateString();

        return match ($feature) {
            'image_generation' => ImageGeneration::query()
                ->where('user_id', $user->id)
                ->whereDate('created_at', $today)
                ->count(),
            'file_intelligence' => FileUpload::query()
                ->where('user_id', $user->id)
                ->whereDate('created_at', $today)
                ->count(),
            'text_analysis' => TextAnalysisRequest::query()
                ->where('user_id', $user->id)
                ->where('status', TextAnalysisRequest::STATUS_COMPLETED)
                ->whereDate('created_at', $today)
                ->count(),
            default => 0,
        };
    }

    /**
     * @return array<string, mixed>
     */
    public function featureSummary(User $user, string $feature): array
    {
        $plan = $this->quota->resolveEffectivePlan($user);
        $enabled = $this->isEnabled($plan, $feature);
        $limit = $enabled ? $this->dailyLimit($plan, $feature) : 0;
        $used = $enabled ? $this->todayUsage($user, $feature) : 0;

        return [
            'enabled' => $enabled,
            'daily_limit' => $limit,
            'daily_used' => $used,
            'daily_remaining' => $limit === null ? null : max(0, $limit - $used),
        ];
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    public function allFeaturesSummary(User $user): array
    {
        $keys = [
            'image_generation',
            'file_intelligence',
            'text_analysis',
            'ai_workspace',
            'memory_ai',
            'voice_ai',
        ];
        $out = [];
        foreach ($keys as $key) {
            $out[$key] = $this->featureSummary($user, $key);
        }

        return $out;
    }

    public function assertCanUse(User $user, string $feature, string $lockedMessage): void
    {
        $plan = $this->quota->resolveEffectivePlan($user);
        if (! $this->isEnabled($plan, $feature)) {
            throw ValidationException::withMessages([
                'feature' => [$lockedMessage],
            ]);
        }

        $limit = $this->dailyLimit($plan, $feature);
        if ($limit === null) {
            return;
        }

        $used = $this->todayUsage($user, $feature);
        if ($used >= $limit) {
            throw ValidationException::withMessages([
                'feature' => [
                    'وصلت إلى الحد اليومي لهذه الأداة ('.$limit.'). جرّب غداً أو رقِّ إلى خطة أعلى.',
                ],
            ]);
        }
    }
}
