<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Recruiter invitations — Agency Owner invites by email before the invitee
 * has an account; on acceptance, a users row is created and linked. This
 * is distinct from the users table itself (which only holds accounts that
 * already exist).
 */
class CreateRecruiterInvitations extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id'            => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'agency_id'     => ['type' => 'BIGINT', 'unsigned' => true],
            'invited_by'    => ['type' => 'BIGINT', 'unsigned' => true],
            'email'         => ['type' => 'VARCHAR', 'constraint' => 150],
            'role_id'       => ['type' => 'BIGINT', 'unsigned' => true],
            'token'         => ['type' => 'VARCHAR', 'constraint' => 255],
            'status'        => ['type' => 'ENUM', 'constraint' => ['pending', 'accepted', 'revoked', 'expired'], 'default' => 'pending'],
            'expires_at'    => ['type' => 'TIMESTAMP'],
            'accepted_at'   => ['type' => 'TIMESTAMP', 'null' => true],
            'created_at'    => ['type' => 'TIMESTAMP', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('token');
        $this->forge->addKey(['agency_id', 'status']);
        $this->forge->addForeignKey('agency_id', 'agencies', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('invited_by', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('role_id', 'roles', 'id', false, 'RESTRICT');
        $this->forge->createTable('recruiter_invitations', true, ['ENGINE' => 'InnoDB']);
    }

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