<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @package seek_quarry\test
 */
namespace seekquarry\yioop\tests;

use seekquarry\yioop\configs as C;
use seekquarry\yioop\library\UnitTest;
use seekquarry\yioop\models\RoleModel;
use seekquarry\yioop\models\ProfileModel;
use seekquarry\yioop\models\datasources\Sqlite3Manager;

/**
 * Checks how RoleModel stores per-role group limits and how it resolves the
 * effective limit for a user account across the roles that account holds.
 * The core rule under test is that the most generous role wins, unlimited
 * (-1) beats any finite cap, and a role with no stored limits row, or an
 * account with no roles at all, counts as unlimited.
 *
 * @author Chris Pollett
 */
class RoleLimitsTest extends UnitTest
{
    /**
     * The RoleModel instance under test, pointed at a throwaway database.
     * @var RoleModel
     */
    public $model;
    /**
     * File path of the throwaway SQLite database this test stands up.
     * @var string
     */
    public $public_db_path;
    /**
     * Stands up a throwaway SQLite database with the ROLE, ROLE_LIMITS, and
     * USER_ROLE tables, seeds three roles (Admin unlimited, User and Editor
     * with finite caps) plus a fourth role with no limits row, and assigns a
     * handful of test accounts to those roles.
     */
    public function setUp()
    {
        $tag = getmypid() . "_" . random_int(1000, 9999);
        $this->public_db_path = C\WORK_DIRECTORY . "/temp/" .
            "role_limits_test_public_$tag.db";
        $public_db = new Sqlite3Manager();
        $public_db->connect("", "", "", $this->public_db_path);
        /* Stand up the ROLE, ROLE_LIMITS, and USER_ROLE tables from the same
           definitions the live database uses, borrowed from ProfileModel, so
           this test tracks any schema change automatically rather than
           carrying a hand-copied version that could drift. */
        $dbinfo = ["DBMS" => "Sqlite3", "DB_HOST" => ""];
        $profile = new ProfileModel(C\DB_NAME, false);
        $profile->initializeSql($public_db, $dbinfo);
        foreach (['ROLE', 'ROLE_LIMITS', 'USER_ROLE'] as $table) {
            $public_db->execute($profile->create_statements[$table]);
        }
        $public_db->execute("INSERT INTO ROLE VALUES (1, 'Admin'), " .
            "(2, 'User'), (3, 'Editor'), (4, 'Guest')");
        $this->model = new RoleModel(C\DB_NAME, false);
        $this->model->db = $public_db;
        $this->model->setRoleLimits(1,
            $this->makeCaps(-1, -1, -1, -1, -1, -1, -1));
        $this->model->setRoleLimits(2,
            $this->makeCaps(3, 50, 500, 26214400, 500, 25, 5000));
        $this->model->setRoleLimits(3,
            $this->makeCaps(10, 100, 500, 26214400, 5000, 100, 50000));
        /* role 4 (Guest) is left with no ROLE_LIMITS row on purpose */
        $public_db->execute("INSERT INTO USER_ROLE (USER_ID, ROLE_ID) " .
            "VALUES (10, 2), (11, 1), (11, 2), (12, 2), (12, 3), " .
            "(14, 2), (14, 4)");
    }
    /**
     * Disconnects and removes the throwaway database, and evicts this test's
     * own handle from the data-source layer's process-wide connection cache
     * so a later test reusing the same scratch name gets a fresh handle.
     */
    public function tearDown()
    {
        if ($this->model && $this->model->db) {
            $this->model->db->disconnect();
            unset(Sqlite3Manager::$active_connections[
                $this->model->db->connect_string]);
        }
        if ($this->public_db_path &&
                file_exists($this->public_db_path)) {
            unlink($this->public_db_path);
        }
    }
    /**
     * Builds a caps array in the shape setRoleLimits expects.
     *
     * @param int $groups groups a role may own
     * @param int $members members allowed per group
     * @param int $wiki wiki pages allowed per group
     * @param int $memory resource memory per page, in bytes
     * @param int $threads threads or chats allowed per group
     * @param int $thread_resources resources allowed per thread
     * @param int $thread_posts posts allowed per thread
     * @param int $cost cost of the role in credits
     * @param string $frequency how often the cost is charged
     * @return array cap column name => value
     */
    public function makeCaps($groups, $members, $wiki, $memory, $threads,
        $thread_resources, $thread_posts, $cost = 0, $frequency = 'never')
    {
        return ['MAX_GROUPS_OWNED' => $groups,
            'MAX_GROUP_MEMBERS' => $members,
            'MAX_GROUP_WIKI_PAGES' => $wiki,
            'MAX_PAGE_RESOURCE_MEMORY' => $memory,
            'MAX_GROUP_THREADS' => $threads,
            'MAX_THREAD_RESOURCES' => $thread_resources,
            'MAX_THREAD_POSTS' => $thread_posts,
            'ROLE_COST' => $cost,
            'CHARGE_FREQUENCY' => $frequency];
    }
    /**
     * Storing a role's caps and reading them back returns the same values,
     * and writing again for the same role replaces rather than duplicates.
     */
    public function setAndGetRoleLimitsTestCase()
    {
        $limits = $this->model->getRoleLimits();
        $this->assertEqual(50, (int)$limits[2]['MAX_GROUP_MEMBERS'],
            "stored User members cap reads back");
        $this->assertEqual(26214400,
            (int)$limits[2]['MAX_PAGE_RESOURCE_MEMORY'],
            "stored User memory cap reads back");
        $this->model->setRoleLimits(2,
            $this->makeCaps(1, 250, 100, 5242880, 50, 5, 100));
        $limits = $this->model->getRoleLimits();
        $this->assertEqual(250, (int)$limits[2]['MAX_GROUP_MEMBERS'],
            "rewriting a role's caps replaces the old value");
    }
    /**
     * An account holding an unlimited role and a finite role is unlimited on
     * that cap, because unlimited is the most generous value.
     */
    public function unlimitedWinsTestCase()
    {
        $effective = $this->model->getUserGroupLimits(11);
        $this->assertEqual(-1, $effective['MAX_GROUP_MEMBERS'],
            "admin (unlimited) plus user (50) resolves to unlimited");
    }
    /**
     * When every role an account holds is finite, the effective cap is the
     * largest across those roles.
     */
    public function maxOverRolesTestCase()
    {
        $effective = $this->model->getUserGroupLimits(12);
        $this->assertEqual(100, $effective['MAX_GROUP_MEMBERS'],
            "user (50) plus editor (100) resolves to 100");
    }
    /**
     * An account holding a single finite role gets that role's caps.
     */
    public function singleRoleTestCase()
    {
        $effective = $this->model->getUserGroupLimits(10);
        $this->assertEqual(50, $effective['MAX_GROUP_MEMBERS'],
            "user-only account gets the user members cap");
        $this->assertEqual(500, $effective['MAX_GROUP_WIKI_PAGES'],
            "user-only account gets the user wiki cap");
    }
    /**
     * An account with no roles at all is unlimited on every cap.
     */
    public function noRolesUnlimitedTestCase()
    {
        $effective = $this->model->getUserGroupLimits(13);
        $this->assertEqual(-1, $effective['MAX_GROUP_MEMBERS'],
            "account with no roles is unlimited");
    }
    /**
     * A role with no stored limits row counts as unlimited, so an account
     * holding such a role alongside a finite role is unlimited on that cap.
     */
    public function missingLimitsRowTestCase()
    {
        $effective = $this->model->getUserGroupLimits(14);
        $this->assertEqual(-1, $effective['MAX_GROUP_MEMBERS'],
            "a role with no limits row lifts the cap to unlimited");
    }
    /**
     * A role's cost and charge frequency round-trip through storage, and a
     * later write replaces them in place rather than adding a second row.
     */
    public function costAndFrequencyTestCase()
    {
        $this->model->setRoleLimits(2,
            $this->makeCaps(3, 50, 500, 26214400, 500, 10, 5000, 25,
            'monthly'));
        $limits = $this->model->getRoleLimits();
        $this->assertEqual(25, (int)$limits[2]['ROLE_COST'],
            "stored role cost reads back");
        $this->assertEqual('monthly', $limits[2]['CHARGE_FREQUENCY'],
            "stored charge frequency reads back");
    }
}
