<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

defined('ABSPATH') || exit;

class AdminNoticeStore
{
    private const TTL = 120;

    public static function push(string $scope, string $message, string $type = 'error') : void
    {
        $userId = get_current_user_id();
        if ($userId <= 0) {
            return;
        }

        $key = self::key($scope, $userId);
        $notices = get_transient($key);
        if (! is_array($notices)) {
            $notices = [];
        }

        $notices[] = [
            'message' => $message,
            'type' => in_array($type, ['success', 'warning', 'info', 'error'], true) ? $type : 'error',
        ];

        set_transient($key, $notices, self::TTL);
    }

    public static function consume(string $scope) : array
    {
        $userId = get_current_user_id();
        if ($userId <= 0) {
            return [];
        }

        $key = self::key($scope, $userId);
        $notices = get_transient($key);
        delete_transient($key);

        return is_array($notices) ? $notices : [];
    }

    private static function key(string $scope, int $userId) : string
    {
        return 'apd_admin_notice_' . $userId . '_' . md5($scope);
    }
}
