<?php

namespace App\Http\Middleware;

use App\Enums\ApprovalStatusEnum;
use App\Enums\UserTypeEnum;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureProviderIsAccepted
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (! $user || $user->type !== UserTypeEnum::PROVIDER) {
            return $next($request);
        }

        $provider = $user->provider;

        if (! $provider) {
            return $this->forbidden(__('auth.registration_incomplete'));
        }

        if ($provider->approval_status === ApprovalStatusEnum::PENDING) {
            return response()->json([
                'payload' => ['approval_status' => ApprovalStatusEnum::PENDING->value],
                'message' => __('auth.provider_pending'),
            ], 202);
        }

        if ($provider->approval_status === ApprovalStatusEnum::REJECTED) {
            return $this->forbidden(__('auth.provider_rejected'));
        }

        return $next($request);
    }

    private function forbidden(string $message): JsonResponse
    {
        return response()->json(['message' => $message], 403);
    }
}
