<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * BATCH 2 — T-07
 * ptm_validation_rules: Aturan validasi beban kerja yang data-driven.
 * Jantung dari validation engine PTM — aturan disimpan sebagai data, bukan hardcoded.
 */
class CreatePtmValidationRules extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id'                    => ['type' => 'INT',     'constraint' => 10,  'unsigned' => true, 'auto_increment' => true],
            'regulation_package_id' => ['type' => 'INT',     'constraint' => 10,  'unsigned' => true, 'null' => false],
            'rule_key'              => ['type' => 'VARCHAR', 'constraint' => 100, 'null' => false, 'comment' => 'min_equiv_hours_certified, max_hours_per_day'],
            'rule_type'             => [
                'type'       => 'ENUM',
                'constraint' => ['MIN_TOTAL_EQUIVALENT_HOURS','MAX_TOTAL_EQUIVALENT_HOURS','MAX_HOURS_PER_DAY','MAX_ADDITIONAL_HOURS','COMPETENCY_CHECK'],
                'null'       => false,
            ],
            'applies_to_condition'  => ['type' => 'VARCHAR', 'constraint' => 50,  'null' => true, 'comment' => 'certified | not_certified | NULL (semua) | kepegawaian:PNS'],
            'rule_value'            => ['type' => 'VARCHAR', 'constraint' => 20,  'null' => false, 'comment' => 'Nilai numerik: 24, 40, 6'],
            'severity'              => ['type' => 'ENUM', 'constraint' => ['ERROR','WARNING','INFO'], 'null' => false, 'default' => 'ERROR'],
            'message_template'      => ['type' => 'VARCHAR', 'constraint' => 500, 'null' => false],
            'is_active'             => ['type' => 'TINYINT', 'constraint' => 1,   'null' => false, 'default' => 1],
            'sort_order'            => ['type' => 'TINYINT', 'constraint' => 3,   'unsigned' => true, 'null' => false, 'default' => 0],
            'created_at'            => ['type' => 'DATETIME', 'null' => true],
            'updated_at'            => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey(['regulation_package_id', 'rule_key']);
        $this->forge->addKey(['regulation_package_id', 'is_active']);
        $this->forge->addKey(['regulation_package_id', 'applies_to_condition']);
        $this->forge->addForeignKey('regulation_package_id', 'ptm_regulation_packages', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('ptm_validation_rules', true);
    }

    public function down(): void
    {
        $this->forge->dropTable('ptm_validation_rules', true);
    }
}
