<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Services\Parents\PrimaryParentUserResolver;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * legacy route filter `auth:parent`.
 *
 * Allows access for any caller that ultimately maps to a primary parent
 * record: the primary parent themselves (parent role / user_type=primary),
 * a registered second parent (user_type=secondary) or an authorized user
 * (user_type=tertiary). The resolved primary parent id is stashed on the
 * request as `primary_parent_id` for controllers to consume.
 */
class EnsureParentProgressAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var User|null $user */
        $user = Auth::user();
        if (! $user) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

        if (in_array('parent', $roles, true)) {
            $request->attributes->set('primary_parent_id', (int) $user->id);

            return $next($request);
        }

        $userType = strtolower(trim((string) ($user->user_type ?? '')));
        if (in_array($userType, ['secondary', 'tertiary'], true)) {
            /** @var PrimaryParentUserResolver $resolver */
            $resolver = app(PrimaryParentUserResolver::class);
            $primaryId = $resolver->resolveFromCredentials((int) $user->id, $userType);
            if ($primaryId !== null && $primaryId > 0) {
                $request->attributes->set('primary_parent_id', $primaryId);

                return $next($request);
            }
        }

        return response()->json(['message' => 'Forbidden.'], 403);
    }
}
