<?php

namespace App\Modules\Wallet\Services;

use App\Http\Resources\WalletTransactionResource;
use App\Models\Setting;
use App\Modules\Users\Models\User;
use App\Modules\Wallet\Models\WalletTransaction;
use App\Modules\Wallet\Repositories\Contracts\WalletTransactionRepositoryInterface;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

/**
 * قراءة المحفظة والمعاملات (Flutter).
 */
final class WalletService
{
    public function __construct(
        private readonly WalletTransactionRepositoryInterface $transactions,
    ) {}

    /**
     * رصيد + نقاط + آخر معاملات (لـ GET /wallet).
     *
     * @return array{balance: string, reward_points: int, recent_transactions: array<int, mixed>}
     */
    public function walletDashboard(User $user, int $recentLimit = 10): array
    {
        $recent = WalletTransaction::query()
            ->where('user_id', $user->id)
            ->latest('id')
            ->limit($recentLimit)
            ->get();

        return [
            'balance' => number_format((float) $user->wallet_balance, 2, '.', ''),
            'reward_points' => (int) $user->reward_points,
            'recent_transactions' => WalletTransactionResource::collection($recent)->resolve(),
        ];
    }

    /**
     * @return array{items: array<int, mixed>, meta: array<string, mixed>}
     */
    public function paginatedTransactions(User $user, int $perPage = 15): array
    {
        $page = $this->transactions->paginateForUser($user->id, $perPage);

        return $this->formatPaginator($page);
    }

    /**
     * نقاط المستخدم + معاملات المكافآت + تلميح الإحالة (مستقبلاً).
     *
     * @return array<string, mixed>
     */
    public function rewardsPayload(User $user, int $perPage = 15): array
    {
        $settings = Setting::current();
        $page = $this->transactions->paginateRewardsForUser($user->id, $perPage);

        $paginated = $this->formatPaginator($page);

        return [
            'reward_points' => (int) $user->reward_points,
            'referral' => [
                'bonus_points_config' => (int) $settings->referral_bonus_points,
                'referral_program_active' => false,
                'message' => 'سيتم ربط نظام الإحالة لاحقاً من تطبيق فلاتر.',
            ],
            'reward_transactions' => [
                'items' => $paginated['items'],
                'meta' => $paginated['meta'],
            ],
        ];
    }

    /**
     * @return array{items: array<int, mixed>, meta: array<string, mixed>}
     */
    private function formatPaginator(LengthAwarePaginator $paginator): array
    {
        $items = collect($paginator->items())
            ->map(fn ($model) => (new WalletTransactionResource($model))->resolve())
            ->values()
            ->all();

        return [
            'items' => $items,
            'meta' => [
                'current_page' => $paginator->currentPage(),
                'last_page' => $paginator->lastPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
            ],
        ];
    }
}
