<?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\tests
 */
namespace seekquarry\yioop\tests;

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

/**
 * Checks the pieces that make roles sellable: listing the roles that
 * carry a price, granting a role with an expiry, and having a lapsed
 * grant stop conferring the role's activities while an active grant
 * still does.
 *
 * @author Chris Pollett
 */
class RoleSubscriptionTest extends UnitTest
{
    /**
     * A throwaway Sqlite3 database built from ProfileModel definitions.
     * @var object
     */
    public $db;
    /**
     * File path of the throwaway database.
     * @var string
     */
    public $db_path;
    /**
     * RoleModel wired to the throwaway database.
     * @var object
     */
    public $role_model;
    /**
     * UserModel wired to the throwaway database.
     * @var object
     */
    public $user_model;
    /**
     * Builds a throwaway database with a free role, a one-time sellable
     * role, and a subscription role, then grants the subscription role
     * to three users with expired, forever, and future expiry times.
     */
    public function setUp()
    {
        $tag = uniqid();
        $this->db_path = C\WORK_DIRECTORY . "/temp/role_sub_$tag.db";
        $this->db = new Sqlite3Manager();
        $this->db->connect("", "", "", $this->db_path);
        $dbinfo = ["DBMS" => "Sqlite3", "DB_HOST" => ""];
        $profile = new ProfileModel(C\DB_NAME, false);
        $profile->initializeSql($this->db, $dbinfo);
        foreach (['ROLE', 'ROLE_LIMITS', 'USER_ROLE', 'ACTIVITY',
            'ROLE_ACTIVITY'] as $table) {
            $this->db->execute($profile->create_statements[$table]);
        }
        $this->role_model = new RoleModel(C\DB_NAME, false);
        $this->role_model->db = $this->db;
        $this->user_model = new UserModel(C\DB_NAME, false);
        $this->user_model->db = $this->db;
        /* role 10 free, role 11 one-time buy, role 12 monthly
           subscription; price and frequency live on ROLE_LIMITS */
        $roles = [[10, 'Free'], [11, 'Lifetime'], [12, 'Monthly']];
        foreach ($roles as $role) {
            $this->db->execute(
                "INSERT INTO ROLE (ROLE_ID, NAME) VALUES (?, ?)", $role);
        }
        $limits = [[10, 0, 'never'], [11, 100, 'once'],
            [12, 50, 'monthly']];
        foreach ($limits as $limit) {
            $this->db->execute("INSERT INTO ROLE_LIMITS " .
                "(ROLE_ID, ROLE_COST, CHARGE_FREQUENCY) " .
                "VALUES (?, ?, ?)", $limit);
        }
        /* one activity that role 12 grants */
        $this->db->execute("INSERT INTO ACTIVITY " .
            "(ACTIVITY_ID, TRANSLATION_ID, METHOD_NAME) " .
            "VALUES (1, 1, 'testActivity')");
        $this->db->execute("INSERT INTO ROLE_ACTIVITY " .
            "(ROLE_ID, ACTIVITY_ID, ALLOWED_ARGUMENTS) " .
            "VALUES (12, 1, 'all')");
        /* user 5 lapsed, user 6 never lapses, user 7 still in future */
        $this->role_model->addUserRole(5, 12, time() - 100);
        $this->role_model->addUserRole(6, 12, C\FOREVER);
        $this->role_model->addUserRole(7, 12, time() + 100000);
    }
    /**
     * Disconnects and removes the throwaway database.
     */
    public function tearDown()
    {
        if ($this->db) {
            $this->db->disconnect();
        }
        if ($this->db_path && file_exists($this->db_path)) {
            unlink($this->db_path);
        }
    }
    /**
     * Only roles with a price above zero are listed as sellable.
     */
    public function getSellableRolesTestCase()
    {
        $sellable = $this->role_model->getSellableRoles();
        $ids = [];
        foreach ($sellable as $role) {
            $ids[] = (int)$role['ROLE_ID'];
        }
        sort($ids);
        $this->assertEqual([11, 12], $ids,
            "free role is excluded, priced roles are listed");
    }
    /**
     * A granted role stores the expiry it was given.
     */
    public function addUserRoleStoresExpiryTestCase()
    {
        $result = $this->db->execute("SELECT EXPIRES FROM USER_ROLE " .
            "WHERE USER_ID = 6 AND ROLE_ID = 12");
        $row = $this->db->fetchArray($result);
        $this->assertEqual(C\FOREVER, (int)$row['EXPIRES'],
            "a forever grant records the forever sentinel");
    }
    /**
     * A lapsed grant stops conferring the role's activity, while a
     * forever grant and a future-dated grant still confer it.
     */
    public function lapsedRoleLosesActivityTestCase()
    {
        $this->assertFalse(
            $this->user_model->isAllowedUserActivity(5, 'testActivity'),
            "expired grant no longer confers the activity");
        $this->assertTrue(
            $this->user_model->isAllowedUserActivity(6, 'testActivity'),
            "forever grant still confers the activity");
        $this->assertTrue(
            $this->user_model->isAllowedUserActivity(7, 'testActivity'),
            "future-dated grant still confers the activity");
    }
    /**
     * A user's held sellable roles come back with their cost, frequency,
     * and expiry; a user holding no sellable role gets an empty list.
     */
    public function getUserSellableRolesTestCase()
    {
        $held = $this->role_model->getUserSellableRoles(6);
        $this->assertEqual(1, count($held),
            "user 6 holds one sellable role");
        $this->assertEqual(12, (int)$held[0]['ROLE_ID'],
            "the held sellable role is the monthly one");
        $this->assertEqual(50, (int)$held[0]['ROLE_COST'],
            "its cost comes from ROLE_LIMITS");
        $this->assertEqual('monthly', $held[0]['CHARGE_FREQUENCY'],
            "its frequency comes from ROLE_LIMITS");
        $this->assertEqual([],
            $this->role_model->getUserSellableRoles(99),
            "a user with no sellable role gets an empty list");
    }
    /**
     * Moving a grant's expiry forward updates the stored value.
     */
    public function updateUserRoleExpiresTestCase()
    {
        $this->role_model->updateUserRoleExpires(6, 12, 12345);
        $result = $this->db->execute("SELECT EXPIRES FROM USER_ROLE " .
            "WHERE USER_ID = 6 AND ROLE_ID = 12");
        $row = $this->db->fetchArray($result);
        $this->assertEqual(12345, (int)$row['EXPIRES'],
            "expiry was moved to the new value");
    }
    /**
     * A new grant renews by default, and setUserRoleRenew can turn that
     * off so a cancelled subscription is later removed rather than
     * renewed.
     */
    public function willRenewDefaultAndSetTestCase()
    {
        $held = $this->role_model->getUserSellableRoles(7);
        $this->assertEqual(1, (int)$held[0]['WILL_RENEW'],
            "a fresh grant renews by default");
        $this->role_model->setUserRoleRenew(7, 12, 0);
        $held = $this->role_model->getUserSellableRoles(7);
        $this->assertEqual(0, (int)$held[0]['WILL_RENEW'],
            "cancelling turns renewing off");
        $this->role_model->setUserRoleRenew(7, 12, 1);
        $held = $this->role_model->getUserSellableRoles(7);
        $this->assertEqual(1, (int)$held[0]['WILL_RENEW'],
            "resubscribing turns renewing back on");
    }
    /**
     * A grant added with the renew flag off keeps that flag, so a caller
     * can grant a role that will not auto-renew.
     */
    public function addUserRoleStoresRenewTestCase()
    {
        $this->role_model->addUserRole(8, 12, time() + 100000, 0);
        $held = $this->role_model->getUserSellableRoles(8);
        $this->assertEqual(1, count($held),
            "user 8 now holds the monthly role");
        $this->assertEqual(0, (int)$held[0]['WILL_RENEW'],
            "the grant kept the renew-off flag it was added with");
    }
}
