<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Financial\Models\Wallet;
use App\Http\Controllers\Controller;
use App\Domain\Participant\Models\Participant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WalletController extends Controller
{
    public function balance(string $participantUuid, Request $request): JsonResponse
    {
        $participant = $this->findAuthorized($participantUuid, $request->user());

        $wallet = Wallet::where('owner_type', 'App\\Domain\\Participant\\Models\\Participant')
            ->where('owner_id', $participant->id)
            ->first();

        if (!$wallet) {
            return response()->json([
                'data' => [
                    'balance' => 0,
                    'balance_display' => '0.00 ج.م',
                    'currency' => 'EGP',
                    'is_active' => false,
                    'has_wallet' => false,
                ],
            ]);
        }

        return response()->json([
            'data' => [
                'balance' => $wallet->balance,
                'balance_display' => number_format($wallet->balance / 100, 2) . ' ج.م',
                'currency' => $wallet->currency ?? 'EGP',
                'is_active' => $wallet->is_active,
                'has_wallet' => true,
            ],
        ]);
    }

    public function transactions(string $participantUuid, Request $request): JsonResponse
    {
        $participant = $this->findAuthorized($participantUuid, $request->user());

        $wallet = Wallet::where('owner_type', 'App\\Domain\\Participant\\Models\\Participant')
            ->where('owner_id', $participant->id)
            ->first();

        if (!$wallet) {
            return response()->json([
                'data' => [],
                'meta' => ['current_page' => 1, 'last_page' => 1, 'per_page' => 20, 'total' => 0],
            ]);
        }

        $transactions = $wallet->walletTransactions()
            ->orderByDesc('created_at')
            ->paginate(20);

        return response()->json([
            'data' => $transactions->map(fn ($t) => [
                'id' => $t->uuid,
                'type' => $t->type,
                'direction' => $t->direction,
                'amount' => $t->amount,
                'amount_display' => number_format($t->amount / 100, 2) . ' ج.م',
                'balance_after' => $t->balance_after,
                'balance_after_display' => number_format($t->balance_after / 100, 2) . ' ج.م',
                'description' => $t->description,
                'created_at' => $t->created_at?->toIso8601String(),
            ]),
            'meta' => [
                'current_page' => $transactions->currentPage(),
                'last_page' => $transactions->lastPage(),
                'per_page' => $transactions->perPage(),
                'total' => $transactions->total(),
            ],
        ]);
    }

    private function findAuthorized(string $uuid, $user): Participant
    {
        $participant = Participant::where('uuid', $uuid)->firstOrFail();
        $personId = $user->person_id;

        if (!$personId) {
            abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
        }

        if ($participant->person_id === $personId) {
            return $participant;
        }

        $guardian = \App\Domain\Identity\Models\Guardian::where('person_id', $personId)->first();
        if ($guardian && $guardian->participants()->where('participants.id', $participant->id)->exists()) {
            return $participant;
        }

        abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
    }
}
