<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Exception;

class AsSetFormat implements Rule
{

    private $strict = true;

    public function __construct(bool $_strict = true)
    {
        $this->strict = $_strict;
    }

    public static function make(bool $strict = true)
    {
        return new static($strict);
    }


    public function passes($attribute, $value)
    {

        if (!is_scalar($value)) {
            return false;
        }

        try {

            if($this->strict) {
                return preg_match('/^AS\d+:AS-[A-Z0-9\-]+$/iD', (string) $value) === 1;
            }

            // Loose variant: an AS-SET-ish token (letters, digits, colons and
            // dashes only) that carries at least one letter/colon/dash, so a
            // bare number is rejected. Anchored so freeform text or stray
            // characters cannot slip through into downstream RADb payloads.
            return preg_match('/^(?=.*[A-Z:\-])[A-Z0-9:\-]+$/iD', (string) $value) === 1;
        }
        catch(Exception $ex) {
            return false;
        }

    }

    public function message()
    {
        return 'The :attribute must be a valid AS-SET.';
    }
}
