<?php

namespace App\Console\Commands;

use App\Models\Central\Tenant;
use App\Services\Tenancy\TenantProvisioner;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class ProvisionTenant extends Command
{
    protected $signature = 'tenants:provision
        {name : The tenant/company display name}
        {slug? : Workspace slug — the first URL path segment (defaults to a slug of the name)}
        {--admin-name= : Admin full name}
        {--admin-email= : Admin email}
        {--password= : Admin password (defaults to "password" if omitted)}';

    protected $description = 'Create and fully provision a new tenant (roles, lookups, entitlements, admin user).';

    public function handle(TenantProvisioner $provisioner): int
    {
        $name = (string) $this->argument('name');
        $slug = Str::slug((string) ($this->argument('slug') ?: $name));
        $adminName = (string) ($this->option('admin-name') ?: 'Administrator');
        $adminEmail = (string) ($this->option('admin-email') ?: "admin@{$slug}.local");

        $validator = Validator::make(
            ['slug' => $slug, 'admin_email' => $adminEmail],
            [
                'slug' => ['required', 'alpha_dash', 'max:63', Rule::unique('tenants', 'slug'), Rule::notIn(config('tenancy.reserved_slugs', []))],
                'admin_email' => ['required', 'email'],
            ],
        );

        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return self::FAILURE;
        }

        $tenant = Tenant::create([
            'name' => $name,
            'slug' => $slug,
            'status' => Tenant::STATUS_ACTIVE,
        ]);

        $result = $provisioner->provision($tenant, [
            'name' => $adminName,
            'email' => $adminEmail,
            'password' => $this->option('password') ?: null,
        ]);

        $this->info("Tenant '{$name}' provisioned.");
        $this->table(['Field', 'Value'], [
            ['Tenant ID', $tenant->id],
            ['Workspace', $tenant->url()],
            ['Admin email', $adminEmail],
            ['Admin password', $result['password']],
        ]);
        $this->warn('Store the admin password now — it is not shown again.');

        return self::SUCCESS;
    }
}
