<?php

namespace App\Services;

use Illuminate\Support\Facades\Session;

class IntendedUrlResolver
{
    // Flat keys — using a dotted child of `url.intended` would collide with
    // Laravel's redirect()->guest() which stores a string at `url.intended`.
    private const ADMIN_KEY = 'auth_intended_admin';

    private const CLIENT_KEY = 'auth_intended_client';

    private const GLOBAL_KEY = 'url.intended';

    public static function stash(string $scope, string $url): void
    {
        $key = $scope === 'admin' ? self::ADMIN_KEY : self::CLIENT_KEY;
        Session::put($key, $url);
    }

    public static function pullForAdmin(string $default): string
    {
        $url = Session::pull(self::ADMIN_KEY);
        Session::forget(self::CLIENT_KEY);
        Session::forget(self::GLOBAL_KEY);

        return $url && self::isAdminPath($url) ? $url : $default;
    }

    public static function pullForClient(string $default): string
    {
        $url = Session::pull(self::CLIENT_KEY);
        Session::forget(self::ADMIN_KEY);
        Session::forget(self::GLOBAL_KEY);

        return $url && ! self::isAdminPath($url) ? $url : $default;
    }

    private static function isAdminPath(string $url): bool
    {
        $path = parse_url($url, PHP_URL_PATH) ?? '';

        return $path === '/admin' || str_starts_with($path, '/admin/');
    }
}
