<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateCitations extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'citing_document_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'comment'    => 'The document that cites another',
            ],
            'cited_document_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'comment'    => 'The document being cited',
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey(['citing_document_id', 'cited_document_id'], false, true); // unique pair
        $this->forge->addKey('cited_document_id'); // index for fast lookup of who cited a document
        $this->forge->addForeignKey('citing_document_id', 'documents', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('cited_document_id', 'documents', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('citations');
    }

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