<?php

namespace Database\Seeders;

use App\Models\Admin;
use App\Models\AdminLimit;
use App\Models\Permission;
use App\Models\RolePermission;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class RbacSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->seedPermissions();
        $this->seedRolePermissions();
        $this->seedDefaultSuperAdmin();
    }

    /**
     * Seed all permissions (admin + client scoped).
     */
    protected function seedPermissions(): void
    {
        $permissions = Permission::getDefaultPermissions();

        foreach ($permissions as $permission) {
            Permission::updateOrCreate(
                ['permission_key' => $permission['permission_key']],
                $permission
            );
        }

        // Ensure existing permissions without scope get proper scope
        Permission::whereNull('scope')->update(['scope' => Permission::SCOPE_ADMIN]);

        $adminCount = Permission::where('scope', Permission::SCOPE_ADMIN)->count();
        $clientCount = Permission::where('scope', Permission::SCOPE_CLIENT)->count();
        $this->command->info("Permissions seeded: {$adminCount} admin-scope, {$clientCount} client-scope.");
    }

    /**
     * Seed role permissions (superadmin, admin, client_owner, client_manager).
     */
    protected function seedRolePermissions(): void
    {
        RolePermission::seedDefaults();
        $this->command->info('Role permissions seeded successfully (including client roles).');
    }

    /**
     * Seed default SuperAdmin account.
     */
    protected function seedDefaultSuperAdmin(): void
    {
        // Check if any superadmin exists
        $existingSuperAdmin = Admin::where('role', Admin::ROLE_SUPERADMIN)->first();

        if ($existingSuperAdmin) {
            // Update existing admin to superadmin if needed
            if ($existingSuperAdmin->role !== Admin::ROLE_SUPERADMIN) {
                $existingSuperAdmin->update(['role' => Admin::ROLE_SUPERADMIN]);
            }
            $this->command->info('Existing SuperAdmin found: ' . $existingSuperAdmin->email);
            return;
        }

        // Create default SuperAdmin
        $superAdmin = Admin::create([
            'name' => 'Super Administrator',
            'email' => 'superadmin@autoreplysms.app',
            'password' => Hash::make('SuperAdmin@123'),
            'role' => Admin::ROLE_SUPERADMIN,
            'is_active' => true,
        ]);

        $this->command->info('Default SuperAdmin created:');
        $this->command->info('  Email: superadmin@autoreplysms.app');
        $this->command->info('  Password: SuperAdmin@123');
        $this->command->warn('  ⚠️  Please change this password immediately!');
    }
}
