<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Bootstrap admin login for tenant 1 (Orchid).
 * Username: admin
 * Password: changeme  <-- change on first login
 */
final class SeedAdminUser extends AbstractMigration
{
    public function up(): void
    {
        $tenantId = (int) $this->fetchRow("SELECT tenant_id FROM tenants WHERE subdomain = 'orchid' LIMIT 1")['tenant_id'];
        $roleId   = (int) $this->fetchRow("SELECT role_id FROM roles WHERE code = 'admin' LIMIT 1")['role_id'];

        $this->table('users')->insert([[
            'tenant_id' => $tenantId,
            'role_id'   => $roleId,
            'username'  => 'admin',
            'password'  => password_hash('changeme', PASSWORD_DEFAULT),
            'f_name'    => 'System',
            'l_name'    => 'Admin',
            'email'     => null,
            'status'    => 'active',
        ]])->saveData();
    }

    public function down(): void
    {
        $this->execute("DELETE FROM users WHERE username = 'admin' AND tenant_id IN (SELECT tenant_id FROM tenants WHERE subdomain = 'orchid')");
    }
}
