<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Mobile-app bearer tokens. Same shape as SiteTracker16's api_tokens table.
 * tenant_id is denormalized on this table so ApiToken middleware can populate
 * $_SESSION['tenant_id'] from a single row lookup — no extra JOIN per request.
 */
final class CreatePersonalAccessTokens extends AbstractMigration
{
    public function change(): void
    {
        $this->table('personal_access_tokens', ['id' => 'token_id', 'signed' => false])
            ->addColumn('tenant_id',   'integer', ['signed' => false])
            ->addColumn('user_id',     'integer', ['signed' => false])
            ->addColumn('token_hash',  'string',  ['limit' => 64])
            ->addColumn('name',        'string',  ['limit' => 60,  'default' => 'mobile'])
            ->addColumn('device_id',   'string',  ['limit' => 120, 'null' => true])
            ->addColumn('platform',    'string',  ['limit' => 20,  'null' => true])
            ->addColumn('app_version', 'string',  ['limit' => 20,  'null' => true])
            ->addColumn('last_used_at','datetime',['null' => true])
            ->addColumn('expires_at',  'datetime',['null' => true])
            ->addColumn('created_at',  'datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('revoked_at',  'datetime',['null' => true])
            ->addIndex(['token_hash'], ['unique' => true])
            ->addIndex(['tenant_id', 'user_id'])
            ->addIndex(['expires_at'])
            ->addForeignKey('tenant_id', 'tenants', 'tenant_id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->addForeignKey('user_id',   'users',   'user_id',   ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();

        // Mobile-app push notification tokens. Separate from personal_access_tokens
        // because a user might revoke API access without wanting to lose push, and vice versa.
        $this->table('push_tokens', ['id' => 'push_token_id', 'signed' => false])
            ->addColumn('tenant_id',   'integer', ['signed' => false])
            ->addColumn('user_id',     'integer', ['signed' => false])
            ->addColumn('device_id',   'string',  ['limit' => 120])
            ->addColumn('expo_token',  'string',  ['limit' => 255])
            ->addColumn('platform',    'string',  ['limit' => 20])
            ->addColumn('created_at',  'datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at',  'datetime',['default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
            ->addColumn('revoked_at',  'datetime',['null' => true])
            ->addIndex(['device_id'], ['unique' => true])
            ->addIndex(['tenant_id', 'user_id'])
            ->addForeignKey('tenant_id', 'tenants', 'tenant_id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->addForeignKey('user_id',   'users',   'user_id',   ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();
    }
}
