<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * BATCH 7 — T-16
 * ptm_audit_logs: Catatan perubahan permanen seluruh entitas PTM.
 * HANYA INSERT — tidak pernah UPDATE atau DELETE.
 */
class CreatePtmAuditLogs extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id'          => ['type' => 'BIGINT',  'constraint' => 20,  'unsigned' => true, 'auto_increment' => true],
            'user_id'     => ['type' => 'BIGINT',  'constraint' => 20,  'unsigned' => true, 'null' => false],
            'entity_type' => ['type' => 'VARCHAR', 'constraint' => 50,  'null' => false, 'comment' => 'PTMAssignment, SKDocument, dst'],
            'entity_id'   => ['type' => 'BIGINT',  'constraint' => 20,  'unsigned' => true, 'null' => false],
            'action'      => [
                'type'       => 'ENUM',
                'constraint' => ['CREATED','UPDATED','LOCKED','OVERRIDDEN','ACTIVATED','EXPIRED','REVOKED','PUBLISHED','SUPERSEDED','REVISED','ARCHIVED','CANCELLED'],
                'null'       => false,
            ],
            'old_data'    => ['type' => 'JSON',    'null' => true, 'comment' => 'State sebelum perubahan'],
            'new_data'    => ['type' => 'JSON',    'null' => true, 'comment' => 'State setelah perubahan'],
            'ip_address'  => ['type' => 'VARCHAR', 'constraint' => 45,  'null' => true],
            'user_agent'  => ['type' => 'VARCHAR', 'constraint' => 255, 'null' => true],
            'created_at'  => ['type' => 'DATETIME', 'null' => false, 'comment' => 'Satu-satunya timestamp — tidak ada updated_at'],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey(['entity_type', 'entity_id']);
        $this->forge->addKey(['user_id', 'created_at']);
        $this->forge->addKey('created_at');
        $this->forge->addKey('action');

        $this->forge->addForeignKey('user_id', 'users', 'id', 'RESTRICT', 'CASCADE');
        $this->forge->createTable('ptm_audit_logs', true);
    }

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