<?php

namespace App\Commands;

use App\Models\Control\TenantRecordModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Tenant\Database\Seeds\DemoHotelSeeder;

/**
 * Provisions a brand-new hotel: creates its database, runs every
 * tenant-schema migration against it, records it in the control DB, and
 * creates the default manager login. Optionally seeds demo data (room
 * types, rooms, a front-desk user) for local development/demos.
 *
 * Usage:
 *   php spark tenant:create --name "MaxYields Demo Hotel" --slug demo \
 *       --admin-email manager@demo.test --admin-password "ChangeMe123!" --demo
 *
 * Any option left out is prompted for interactively.
 */
class TenantCreate extends BaseCommand
{
    protected $group       = 'Tenancy';
    protected $name        = 'tenant:create';
    protected $description = 'Provision a new hotel: creates its database, runs migrations, and creates the manager login.';

    protected $options = [
        '--name'            => 'Hotel name, e.g. "MaxYields Demo Hotel"',
        '--slug'            => 'Subdomain slug, e.g. "demo" (letters, numbers, dashes only)',
        '--admin-name'      => 'Full name for the default manager login (default: "Manager")',
        '--admin-email'     => 'Email for the default manager login',
        '--admin-password'  => 'Password for the default manager login',
        '--demo'            => 'Also seed demo room types, rooms, and a front-desk user',
    ];

    public function run(array $params)
    {
        $name          = $params['name'] ?? CLI::getOption('name') ?? CLI::prompt('Hotel name');
        $slug          = $params['slug'] ?? CLI::getOption('slug') ?? CLI::prompt('Subdomain slug (letters/numbers/dashes)', null, ['required', 'regex_match[/^[a-z0-9-]+$/]']);
        $adminName     = $params['admin-name'] ?? CLI::getOption('admin-name') ?? CLI::prompt('Manager full name', 'Manager');
        $adminEmail    = $params['admin-email'] ?? CLI::getOption('admin-email') ?? CLI::prompt('Manager email', null, ['required', 'valid_email']);
        $adminPassword = $params['admin-password'] ?? CLI::getOption('admin-password') ?? CLI::prompt('Manager password (min 8 chars)', null, ['required', 'min_length[8]']);
        $seedDemo      = array_key_exists('demo', $params) || CLI::getOption('demo') !== null;

        $tenants = new TenantRecordModel();

        if ($tenants->where('slug', $slug)->first() !== null) {
            CLI::error("A tenant with slug \"{$slug}\" already exists.");

            return;
        }

        CLI::write("Provisioning \"{$name}\" ({$slug})...", 'yellow');

        $provisioner = service('tenantProvisioner');
        $tenant      = $provisioner->provision($name, $slug, $adminName, $adminEmail, $adminPassword);

        CLI::write("  Database created: {$tenant->db_name}", 'green');
        CLI::write('  Tenant schema migrated.', 'green');
        CLI::write("  Manager login: {$adminEmail}", 'green');

        if ($seedDemo) {
            CLI::write('Seeding demo data (room types, rooms, front-desk user)...', 'yellow');

            $connection = service('tenantContext')->buildConnectionFor($tenant->db_name);
            $seeder     = new DemoHotelSeeder(config('Database'), $connection);
            $seeder->run();

            CLI::write('  Demo data seeded: 3 room types, 9 rooms.', 'green');
            CLI::write('  Front-desk login: ' . DemoHotelSeeder::FRONT_DESK_EMAIL . ' / ' . DemoHotelSeeder::FRONT_DESK_PASSWORD, 'green');
        }

        CLI::newLine();
        CLI::write('Done. Point your browser at the resolved subdomain, or in local dev set:', 'white');
        CLI::write("  tenant.defaultSlug = {$slug}", 'cyan');
        CLI::write('in .env to make this the fallback tenant.', 'white');
    }
}
