<?php

namespace Velis\Mvc\Controller\Listeners;

use Velis\Api\HttpExceptionHandler\HttpException;
use Velis\App;
use Velis\Filter;
use Velis\Mvc\Controller\Exception\NotFoundException;
use Velis\Mvc\Controller\Listeners\Concrete\AbstractListener;
use Velis\Output;

/**
 * Adds filtered params to session.
 */
class ResolveSessionParamsListener extends AbstractListener
{
    /**
     * Params to apply in a session object
     * @var array<string, string>
     */
    protected static array $sessionParamsFilter = [
        'filtered_complex_id' => 'filterInts'
    ];

    /**
     * @throws NotFoundException
     * @throws HttpException
     */
    public function handle(): void
    {
        if (!$this->request->getHeader('x-session-params')) {
            return;
        }

        $params = Output::jsonDecode($this->request->getHeader('x-session-params'));
        if (session_id()) {
            App::$session->filtered_complex_id = null;
        }

        foreach ($params as $key => $values) {
            if (!array_key_exists($key, self::$sessionParamsFilter)) {
                continue;
            }

            if (method_exists(Filter::class, self::$sessionParamsFilter[$key]) && session_id()) {
                App::$session->{$key} = Filter::{self::$sessionParamsFilter[$key]}($values);
            }
        }
    }
}
