<?php

namespace App\Console\Commands;

use App\Models\Company;
use App\Models\User;
use App\Services\CompanySetupService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;

class EnsureAdminUser extends Command
{
    protected $signature = 'admin:ensure
                            {--email=admin@admin.com : Admin email}
                            {--password=password : Plain password (dev only)}';

    protected $description = 'Create or reset the default company admin user (for local/staging).';

    public function handle(CompanySetupService $setup): int
    {
        if (! Schema::hasTable('roles')) {
            $this->error('The `roles` table does not exist. Create tables first:');
            $this->line('  php artisan migrate');
            $this->newLine();
            $this->comment('Then run this command again, or use: php artisan db:seed');

            return self::FAILURE;
        }

        foreach (['admin', 'manager', 'sales_agent'] as $role) {
            Role::findOrCreate($role, 'web');
        }

        $email = strtolower(trim((string) $this->option('email')));
        $plain = (string) $this->option('password');

        $company = Company::firstOrCreate(
            ['name' => 'Admin Company'],
            ['plan' => 'free']
        );

        if ($company->pipelineStages()->count() === 0) {
            $setup->seedDefaultPipeline($company);
        }

        $user = User::firstOrNew(['email' => $email]);
        $user->company_id = $company->id;
        $user->name = $user->exists ? $user->name : 'Administrator';
        $user->password = $plain;
        $user->save();

        $user->syncRoles(['admin']);

        $this->info('Admin ready: '.$email.' / (password you passed with --password)');

        return self::SUCCESS;
    }
}
