<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateConnections extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id'                 => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'requester_user_id'  => ['type' => 'BIGINT', 'unsigned' => true],
            'recipient_user_id'  => ['type' => 'BIGINT', 'unsigned' => true],
            'status'             => ['type' => 'ENUM', 'constraint' => ['pending', 'accepted', 'rejected'], 'default' => 'pending'],
            'created_at'         => ['type' => 'TIMESTAMP', 'null' => true],
            'responded_at'       => ['type' => 'TIMESTAMP', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        // One request row per direction; the service layer checks BOTH
        // directions before creating a new one so a pair of users can
        // never end up with two simultaneous pending requests to each other.
        $this->forge->addUniqueKey(['requester_user_id', 'recipient_user_id']);
        $this->forge->addKey(['recipient_user_id', 'status']);
        $this->forge->addForeignKey('requester_user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('recipient_user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('connections', true, ['ENGINE' => 'InnoDB']);
    }

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