<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\Tenant;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class CreateSuperAdmin extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'make:superadmin {email?} {password?}';

    /**
     * The console command description.
     */
    protected $description = 'Create a super admin user with access to all tenants';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $email = $this->argument('email') ?: 'superadmin@admin.com';
        $password = $this->argument('password') ?: 'superadmin123';

        // Create default tenant if it doesn't exist
        $defaultTenant = Tenant::firstOrCreate([
            'domain' => 'main.store'
        ], [
            'name' => 'Main Store',
            'database' => 'main'
        ]);

        // Create Super Admin role if it doesn't exist
        $superAdminRole = Role::firstOrCreate(['name' => 'Super Admin']);

        // Create essential permissions
        $permissions = [
            'manage users',
            'manage tenants', 
            'manage roles',
            'manage permissions',
            'access all tenants',
            'manage products',
            'manage customers',
            'manage sales',
            'manage expenses',
            'view reports'
        ];

        foreach ($permissions as $permissionName) {
            Permission::firstOrCreate(['name' => $permissionName]);
        }

        // Assign all permissions to Super Admin role
        $superAdminRole->syncPermissions(Permission::all());

        // Delete existing super admin if exists
        User::where('email', $email)->delete();

        // Create super admin user
        $superAdmin = User::create([
            'name' => 'Super Admin',
            'email' => $email,
            'password' => Hash::make($password),
            'tenant_id' => $defaultTenant->id
        ]);

        // Assign Super Admin role
        $superAdmin->assignRole($superAdminRole);

        $this->info('🎉 Super Admin created successfully!');
        $this->info('📧 Email: ' . $email);
        $this->info('🔑 Password: ' . $password);
        $this->info('🏢 Can access ALL tenants');
        $this->info('🌐 Login at: http://127.0.0.1:8001/login');
        
        $this->info("\n✅ Permissions granted:");
        foreach ($permissions as $permission) {
            $this->info("   - " . $permission);
        }
    }
}
