<?php

namespace App\Models\Rule;

use App\Models\BaseModel;

/**
 * TestRule Model
 * 
 * Mapping table linking ruledef to test sites.
 * Represents which tests a rule is linked to.
 */
class TestRuleModel extends BaseModel
{
    protected $table = 'testrule';
    protected $primaryKey = 'TestRuleID';
    protected $allowedFields = [
        'RuleID',
        'TestSiteID',
        'CreateDate',
        'EndDate',
    ];

    protected $useTimestamps = true;
    protected $createdField = 'CreateDate';
    protected $updatedField = '';

    protected $useSoftDeletes = true;
    protected $deletedField = 'EndDate';

    /**
     * Get all active test site mappings for a rule
     *
     * @param int $ruleID The rule ID
     * @return array Array of mappings with test site details
     */
    public function getByRuleID(int $ruleID): array
    {
        return $this->where('RuleID', $ruleID)
            ->where('EndDate IS NULL')
            ->findAll();
    }

    /**
     * Get all active rules mapped to a test site
     *
     * @param int $testSiteID The test site ID
     * @return array Array of mappings
     */
    public function getByTestSiteID(int $testSiteID): array
    {
        return $this->where('TestSiteID', $testSiteID)
            ->where('EndDate IS NULL')
            ->findAll();
    }

    /**
     * Check if a rule is linked to a test site
     *
     * @param int $ruleID The rule ID
     * @param int $testSiteID The test site ID
     * @return bool True if linked and active
     */
    public function isLinked(int $ruleID, int $testSiteID): bool
    {
        return $this->where('RuleID', $ruleID)
            ->where('TestSiteID', $testSiteID)
            ->where('EndDate IS NULL')
            ->countAllResults() > 0;
    }
}
