<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Same shape and purpose as password_reset_codes, deliberately NOT
 * reused for organizer codes: that table's user_id column carries a real
 * hard foreign key to users.id (CASCADE) — inserting an event_organizers
 * id there would be a straight-up FK violation, not just a theoretical
 * id-collision risk, since event_organizers and users auto-increment
 * independently from 1. A parallel table is the correct fix, not a
 * shared one with a discriminator column.
 */
class CreateEventOrganizerPasswordCodesTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'organizer_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
            ],
            'code' => [
                'type'       => 'VARCHAR',
                'constraint' => 6,
            ],
            'expires_at' => [
                'type' => 'DATETIME',
            ],
            'used_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'created_at' => [
                'type' => 'DATETIME',
            ],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('organizer_id');
        $this->forge->addForeignKey('organizer_id', 'event_organizers', 'id', '', 'CASCADE');
        $this->forge->createTable('event_organizer_password_codes');
    }

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