<?php

namespace App\Commands;

use App\Models\Control\TenantRecordModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database as DatabaseConfig;

/**
 * Runs a Tenant\Database\Seeds seeder against one tenant's own database —
 * the tenant-schema counterpart to `php spark db:seed`, which only ever
 * targets the control DB's default connection. Needed because tenant DBs
 * are dynamic connections built per-slug (see TenantContextService), not
 * named groups in Config\Database, so the seeder has to be handed that
 * connection explicitly (see Seeder::__construct()'s $db parameter)
 * rather than relying on a $DBGroup property.
 *
 * Usage:
 *   php spark tenant:seed --slug demo --class DemoDataEnrichmentSeeder
 */
class TenantSeed extends BaseCommand
{
    protected $group       = 'Tenancy';
    protected $name        = 'tenant:seed';
    protected $description = 'Run a Tenant\Database\Seeds seeder against one provisioned hotel database.';

    protected $options = [
        '--slug'  => 'The tenant slug to seed.',
        '--class' => 'The seeder class name (in app/Tenant/Database/Seeds).',
    ];

    public function run(array $params)
    {
        $slug  = $params['slug'] ?? CLI::getOption('slug');
        $class = $params['class'] ?? CLI::getOption('class');

        if (! $slug || ! $class) {
            CLI::error('Pass --slug <slug> --class <SeederClassName>.');

            return;
        }

        $tenant = (new TenantRecordModel())->where('slug', $slug)->where('status', 'active')->first();

        if ($tenant === null) {
            CLI::error("No active tenant found for slug '{$slug}'.");

            return;
        }

        $fqcn = str_contains($class, '\\') ? $class : 'Tenant\\Database\\Seeds\\' . $class;

        if (! class_exists($fqcn)) {
            CLI::error("Seeder class not found: {$fqcn}");

            return;
        }

        CLI::write("Seeding {$tenant->slug} ({$tenant->db_name}) with {$class}...", 'yellow');

        $connection = service('tenantContext')->buildConnectionFor($tenant->db_name);
        $seeder     = new $fqcn(config(DatabaseConfig::class), $connection);
        $seeder->run();

        CLI::write('  Done.', 'green');
    }
}
