<?php

namespace App\Services\Web;

use App\Models\Conversation;
use App\Models\FileUpload;
use App\Models\ImageGeneration;
use App\Modules\Users\Models\User;
use App\Models\UserSubscription;
use App\Services\Subscriptions\AiQuotaService;

final class WebDashboardService
{
    public function __construct(
        private readonly AiQuotaService $aiQuota,
    ) {}

    /**
     * @return array<string, mixed>
     */
    public function overview(User $user): array
    {
        $sub = UserSubscription::query()
            ->with('plan')
            ->where('user_id', $user->id)
            ->where('status', UserSubscription::STATUS_ACTIVE)
            ->orderByDesc('id')
            ->first();
        $plan = $sub?->plan;
        $quota = $this->aiQuota->summaryForApi($user);

        return [
            'user' => $user,
            'subscription' => [
                'plan_name' => $plan?->name ?? 'مجاني',
                'plan_slug' => $plan?->slug ?? 'free',
                'ends_at' => $sub?->ends_at?->toIso8601String(),
            ],
            'ai_messages' => [
                'used' => $quota['daily_used'] ?? 0,
                'limit' => $quota['daily_limit'] ?? 0,
                'remaining' => $quota['daily_remaining'] ?? 0,
            ],
            'wallet_balance' => (float) $user->wallet_balance,
            'reward_points' => (int) $user->reward_points,
            'level' => (int) ($user->level ?? 1),
            'recent_chats' => Conversation::query()
                ->where('user_id', $user->id)
                ->orderByDesc('last_message_at')
                ->limit(5)
                ->get(['id', 'title', 'last_message_at']),
            'recent_images' => ImageGeneration::query()
                ->where('user_id', $user->id)
                ->where('status', ImageGeneration::STATUS_COMPLETED)
                ->orderByDesc('id')
                ->limit(6)
                ->get(['id', 'original_prompt', 'prompt', 'image_url', 'created_at']),
            'recent_files' => FileUpload::query()
                ->where('user_id', $user->id)
                ->orderByDesc('id')
                ->limit(5)
                ->get(['id', 'original_name', 'status', 'created_at']),
        ];
    }
}
