<?php

namespace App\Commands;

use App\Models\Control\TenantRecordModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Database\MigrationRunner;
use Config\Migrations as MigrationsConfig;

/**
 * Runs any pending Tenant\Database\Migrations against one or all already-
 * provisioned tenant databases. `tenant:create` only runs migrations once,
 * at provisioning time — this is what applies schema changes made after a
 * hotel already exists (e.g. every later phase's new tables).
 *
 * Usage:
 *   php spark tenant:migrate --slug demo
 *   php spark tenant:migrate --all
 */
class TenantMigrate extends BaseCommand
{
    protected $group       = 'Tenancy';
    protected $name        = 'tenant:migrate';
    protected $description = 'Run pending tenant-schema migrations against one or all provisioned hotel databases.';

    protected $options = [
        '--slug' => 'Migrate a single tenant by slug',
        '--all'  => 'Migrate every active tenant',
    ];

    public function run(array $params)
    {
        $slug = $params['slug'] ?? CLI::getOption('slug');
        $all  = array_key_exists('all', $params) || CLI::getOption('all') !== null;

        if (! $slug && ! $all) {
            CLI::error('Pass --slug <slug> or --all.');

            return;
        }

        $tenants  = new TenantRecordModel();
        $query    = $tenants->where('status', 'active');
        $records  = $slug ? $query->where('slug', $slug)->findAll() : $query->findAll();

        if (empty($records)) {
            CLI::error('No matching active tenant(s) found.');

            return;
        }

        foreach ($records as $tenant) {
            CLI::write("Migrating {$tenant->slug} ({$tenant->db_name})...", 'yellow');

            $connection = service('tenantContext')->buildConnectionFor($tenant->db_name);
            $runner     = new MigrationRunner(config(MigrationsConfig::class), $connection);
            $runner->setNamespace('Tenant');

            if ($runner->latest('tenant')) {
                CLI::write('  Migrated.', 'green');
            } else {
                CLI::write('  Already up to date.', 'green');
            }
        }
    }
}
