<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Wallet\WalletTransferService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Wallet\StoreTransferRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;

class TransferController extends Controller
{
    public function __construct(private readonly WalletTransferService $walletTransferService)
    {
    }

    public function store(StoreTransferRequest $request): JsonResponse
    {
        $data = $request->validated();

        if (! $data['confirm']) {
            return response()->json(['message' => 'Action not confirmed.'], 422);
        }

        $receiver = User::query()->where('public_id', $data['receiver_public_id'])->firstOrFail();

        $transfer = $this->walletTransferService->transfer(
            sender: $request->user(),
            receiver: $receiver,
            amount: (int) $data['amount'],
            idempotencyKey: $data['idempotency_key'],
            note: $data['note'] ?? null,
            totpCode: $data['totp_code'] ?? null,
        );

        return response()->json(['transfer_id' => $transfer->id, 'status' => $transfer->status]);
    }
}
