<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Rule engine tables: ruledef + testrule.
 *
 * ruleaction is deprecated; actions are embedded in ruledef.ConditionExprCompiled.
 */
class CreateTestRules extends Migration
{
    public function up()
    {
        // ruledef - rule definitions (not linked to specific test)
        $this->forge->addField([
            'RuleID' => ['type' => 'INT', 'unsigned' => true, 'auto_increment' => true],
            'RuleCode' => ['type' => 'VARCHAR', 'constraint' => 50, 'null' => false],
            'RuleName' => ['type' => 'VARCHAR', 'constraint' => 100, 'null' => false],
            'Description' => ['type' => 'VARCHAR', 'constraint' => 255, 'null' => true],
            'EventCode' => ['type' => 'VARCHAR', 'constraint' => 50, 'null' => false],
            'ConditionExpr' => ['type' => 'VARCHAR', 'constraint' => 1000, 'null' => true],
            'ConditionExprCompiled' => ['type' => 'JSON', 'null' => true],
            'CreateDate' => ['type' => 'DATETIME', 'null' => true],
            'StartDate' => ['type' => 'DATETIME', 'null' => true],
            'EndDate' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('RuleID', true);
        $this->forge->addKey('RuleCode');
        $this->forge->addKey('EventCode');
        $this->forge->createTable('ruledef');

        // testrule - mapping table for many-to-many relationship between ruledef and tests
        $this->forge->addField([
            'TestRuleID' => ['type' => 'INT', 'unsigned' => true, 'auto_increment' => true],
            'RuleID' => ['type' => 'INT', 'unsigned' => true, 'null' => false],
            'TestSiteID' => ['type' => 'INT', 'unsigned' => true, 'null' => false],
            'CreateDate' => ['type' => 'DATETIME', 'null' => true],
            'EndDate' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('TestRuleID', true);
        $this->forge->addKey('RuleID');
        $this->forge->addKey('TestSiteID');
        $this->forge->createTable('testrule');

        // Foreign keys for mapping table
        $this->db->query('ALTER TABLE `testrule` ADD CONSTRAINT `fk_testrule_ruledef` FOREIGN KEY (`RuleID`) REFERENCES `ruledef`(`RuleID`) ON DELETE CASCADE ON UPDATE CASCADE');
        $this->db->query('ALTER TABLE `testrule` ADD CONSTRAINT `fk_testrule_testsite` FOREIGN KEY (`TestSiteID`) REFERENCES `testdefsite`(`TestSiteID`) ON DELETE CASCADE ON UPDATE CASCADE');
    }

    public function down()
    {
        $this->forge->dropTable('testrule', true);
        $this->forge->dropTable('ruledef', true);
    }
}
