<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Enums\AccountType;
use App\Enums\UserAccountStatus;
use App\Http\Controllers\Controller;
use App\Http\Resources\Admin\PendingProfessionalResource;
use App\Models\User;
use App\Notifications\AccountApprovedNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

use function in_array;

class AdminController extends Controller
{
    /**
     * § 14 — professionnels dont le compte est en attente de validation.
     */
    public function getPendingProfessionals(Request $request): AnonymousResourceCollection
    {
        $paginator = User::query()
            ->pendingProfessionals()
            ->with(['professionalProfile:id,user_id,professional_name,verification_status,city_id'])
            ->orderBy('created_at')
            ->paginate((int) $request->integer('per_page', 15));

        return PendingProfessionalResource::collection($paginator);
    }

    /**
     * § 14 — valide un professionnel et notifie l’utilisateur par e-mail.
     */
    public function approveProfessional(User $user): JsonResponse
    {
        $this->ensurePendingProfessional($user);

        $user->forceFill([
            'status' => UserAccountStatus::Approved,
        ])->save();

        $user->notify(new AccountApprovedNotification);

        return response()->json([
            'message' => __('Compte validé.'),
            'data' => PendingProfessionalResource::make($user->load('professionalProfile')),
        ]);
    }

    /**
     * § 14 — refuse l’accès métier au professionnel en attente.
     */
    public function rejectProfessional(User $user): JsonResponse
    {
        $this->ensurePendingProfessional($user);

        $user->forceFill([
            'status' => UserAccountStatus::Rejected,
        ])->save();

        return response()->json([
            'message' => __('Compte refusé.'),
            'data' => PendingProfessionalResource::make($user->load('professionalProfile')),
        ]);
    }

    private function ensurePendingProfessional(User $user): void
    {
        $isProfessional = in_array($user->account_type?->value, AccountType::professionalValues(), true);
        $isPending = $user->status === UserAccountStatus::Pending;

        if (! $isProfessional || ! $isPending) {
            abort(422, __('Cet utilisateur n’est pas un professionnel en attente.'));
        }
    }
}
