<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProviderBankAccountStoreRequest;
use App\Http\Requests\ProviderBankAccountUpdateRequest;
use App\Http\Resources\ProviderBankAccountResource;
use App\Models\Provider;
use App\Services\ProviderBankAccountService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class ProviderBankAccountController extends Controller
{
    public function __construct(
        private readonly ProviderBankAccountService $service,
    ) {}

    public function index(): JsonResponse
    {
        $items = $this->service->getAll($this->resolveProvider());

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

    public function store(ProviderBankAccountStoreRequest $request): JsonResponse
    {
        $item = $this->service->create($this->resolveProvider(), $request->validated());

        return $this->successResponse(
            payload: new ProviderBankAccountResource($item),
            message: __('messages.bank_account_created'),
            code:    201,
        );
    }

    public function update(ProviderBankAccountUpdateRequest $request, int $id): JsonResponse
    {
        $item = $this->service->update($this->resolveProvider(), $id, $request->validated());

        return $this->successResponse(
            payload: new ProviderBankAccountResource($item),
            message: __('messages.bank_account_updated'),
        );
    }

    public function destroy(int $id): JsonResponse
    {
        $this->service->delete($this->resolveProvider(), $id);

        return $this->successResponse(message: __('messages.bank_account_deleted'));
    }

    //

    /**
     * Somente o proprio prestador manipula as contas: o id nunca vem da URL.
     */
    public function forProvider(int $providerId): JsonResponse
    {
        $provider = Provider::findOrFail($providerId);

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

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

    //

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

        if (! $provider) {
            abort(403, __('auth.unauthorized'));
        }

        return $provider;
    }
}
