<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\StudentExamService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class StudentWalletController extends Controller
{
    public function __construct(
        private readonly StudentExamService $examService,
    ) {
    }

    public function overview(Request $request): JsonResponse
    {
        return response()->json(
            $this->examService->buildWalletOverviewPayload($request->user())
        );
    }

    public function history(Request $request): JsonResponse
    {
        return response()->json(
            $this->examService->buildWalletHistoryPayload($request->user())
        );
    }

    public function withdrawHistory(Request $request): JsonResponse
    {
        return response()->json(
            $this->examService->buildWithdrawHistoryPayload($request->user())
        );
    }

    public function recharge(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'recharge_amount' => ['required', 'numeric', 'min:1'],
            'transaction_id' => ['required', 'string', 'max:40', Rule::unique('wallethistory', 'transectionid')],
            'attachment_id' => ['required', 'integer'],
        ]);

        $result = $this->examService->submitWalletRechargeRequest(
            $request->user(),
            (float) $validated['recharge_amount'],
            (string) $validated['transaction_id'],
            (int) $validated['attachment_id'],
            $request,
            $request->attributes->get('studentDeviceSession'),
        );

        $statusCode = match ($result['status'] ?? 'invalid_attachment') {
            'submitted' => 201,
            'invalid_attachment', 'duplicate_transaction' => 422,
            default => 422,
        };

        return response()->json($result, $statusCode);
    }

    public function withdraw(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'payment_type' => ['required', Rule::in(['Paytm', 'PhonePe', 'Google Pay'])],
            'mobile_number' => ['required', 'regex:/^[6-9][0-9]{9}$/'],
            'withdraw_amount' => ['required', 'integer', 'min:1', 'max:99999'],
        ]);

        $result = $this->examService->submitWithdrawRequest(
            $request->user(),
            (string) $validated['payment_type'],
            (string) $validated['mobile_number'],
            (float) $validated['withdraw_amount'],
            $request,
            $request->attributes->get('studentDeviceSession'),
        );

        $statusCode = match ($result['status'] ?? 'insufficient_winning') {
            'submitted' => 201,
            'insufficient_winning' => 422,
            default => 422,
        };

        return response()->json($result, $statusCode);
    }
}
