<?php

namespace App\Http\Controllers;

use App\Http\Resources\PaymentSplitResource;
use App\Http\Resources\ProviderWithdrawalResource;
use App\Services\ProviderWithdrawalService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProviderWithdrawalController extends Controller
{
    public function __construct(
        private readonly ProviderWithdrawalService $service,
    ) {}

    public function index(): JsonResponse
    {
        $provider = $this->resolveProvider();

        $items = $this->service->getWithdrawals($provider);

        return $this->successResponse(payload: ProviderWithdrawalResource::collection($items));
    }

    public function all(): JsonResponse
    {
        $items = $this->service->getAllWithdrawals();

        return $this->successResponse(payload: ProviderWithdrawalResource::collection($items));
    }

    public function store(Request $request): JsonResponse
    {
        $provider = $this->resolveProvider();

        $withdrawal = $this->service->requestWithdrawal($provider);

        return $this->successResponse(
            payload: new ProviderWithdrawalResource($withdrawal),
            message: __('messages.withdrawal_requested'),
            code:    201,
        );
    }

    public function show(int $id): JsonResponse
    {
        $provider = $this->resolveProvider();

        $withdrawal = $this->service->getWithdrawal($id, $provider);

        return $this->successResponse(payload: new ProviderWithdrawalResource($withdrawal));
    }

    //

    public function balance(): JsonResponse
    {
        $provider = $this->resolveProvider();

        return $this->successResponse(payload: [
            'available' => $this->service->getAvailableBalance($provider),
            'pending'   => $this->service->getPendingBalance($provider),
        ]);
    }

    public function fees(): JsonResponse
    {
        return $this->successResponse(payload: $this->service->getWithdrawalFees());
    }

    public function splits(): JsonResponse
    {
        $provider = $this->resolveProvider();

        $splits = $this->service->getPaymentSplits($provider);

        return $this->successResponse(payload: PaymentSplitResource::collection($splits));
    }

    //

    private function resolveProvider()
    {
        $provider = Auth::user()->provider;

        if (! $provider) {
            abort(403, 'Apenas prestadores podem acessar este recurso.');
        }

        return $provider;
    }
}
