<?php declare(strict_types=1);
/**
 * @author Ryan Spaeth <rspaeth@spaethtech.com>
 * @copyright 2025 - Spaeth Technologies, Archous Networks
 */

namespace SpaethTech\UCRM\SDK;

final class ContentSecurityPolicy
{
    private array $keywords = [
        "none", "self", "unsafe-inline", "unsafe-eval"
    ];

    public function __construct(
        public readonly string $directive,
        public array $values = []
    )
    {
    }

    public static function parse(string $data): array
    {
        $csps = [];

        $policies = array_filter(array_map("trim", explode(";", $data)));

        foreach($policies as $policy)
        {
            $policy = array_filter(array_map(function($p) {
                return trim(str_replace("\\", "", $p));
            }, explode(" ", $policy)));

            $directive = array_shift($policy);
            $csps[] = new self($directive, $policy);
        }

        //return new self($directive, array_filter(array_map("trim", explode(" ", $value))));
        return $csps;
    }

    public function add(string $value): self
    {
        if(!in_array($value, $this->values))
            $this->values[] = $value;

        return $this;
    }

    public function del(string $value): self
    {
        if (($key = array_search($value, $this->values)) !== false)
            unset($this->values[$key]);

        return $this;
    }

    public function __toString(): string
    {
        if (count($this->values) === 0)
            return ""; // OR 'none' ?

        $values = array_map(function($v) {
            return str_contains($v, "'") ? str_replace("'", "\\'", $v) : $v;
        }, $this->values);

        $values = implode(" ", $values);

        return "$this->directive $values";
    }

}
