<?php

namespace App\Commands;

use App\Models\Control\AdminUserModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * Creates a super-admin (platform operator) login. There's no self-
 * service signup for this — deliberately CLI-only, same reasoning as
 * `tenant:create` having no web UI: the first platform account has to
 * come from somewhere trusted before any web-based admin UI exists to
 * create the next one.
 *
 * Usage:
 *   php spark admin:create --name "Ama Owusu" --email admin@maxyields.com --password "ChangeMe123!"
 */
class AdminUserCreate extends BaseCommand
{
    protected $group       = 'Admin';
    protected $name        = 'admin:create';
    protected $description = 'Create a super-admin (platform operator) login.';

    protected $options = [
        '--name'     => 'Full name',
        '--email'    => 'Login email',
        '--password' => 'Password (min 8 chars)',
    ];

    public function run(array $params)
    {
        $name     = $params['name'] ?? CLI::getOption('name') ?? CLI::prompt('Full name');
        $email    = $params['email'] ?? CLI::getOption('email') ?? CLI::prompt('Email', null, ['required', 'valid_email']);
        $password = $params['password'] ?? CLI::getOption('password') ?? CLI::prompt('Password (min 8 chars)', null, ['required', 'min_length[8]']);

        $admins = new AdminUserModel();

        if ($admins->where('email', $email)->first() !== null) {
            CLI::error("An admin with email \"{$email}\" already exists.");

            return;
        }

        $id = $admins->insert([
            'full_name'     => $name,
            'email'         => $email,
            'password_hash' => password_hash($password, PASSWORD_DEFAULT),
            'role'          => 'super_admin',
            'is_active'     => 1,
        ], true);

        if ($id === false) {
            CLI::error('Could not create admin: ' . implode(' ', $admins->errors()));

            return;
        }

        CLI::write("Super-admin created: {$email}", 'green');
        CLI::write('Sign in at /admin/login', 'white');
    }
}
