<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Facades\DB;

class FixRoles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:roles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix roles and permissions in the system';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Fixing roles and permissions...');

        // 清空角色权限关联表
        DB::table('role_has_permissions')->truncate();

        // 获取所有角色
        $admin = Role::where('name', 'admin')->first();
        $staff = Role::where('name', 'staff')->first();
        $shareholder = Role::where('name', 'shareholder')->first();

        // 确保角色存在
        if (!$admin) {
            $admin = Role::create(['name' => 'admin']);
            $this->info('Created admin role.');
        }

        if (!$staff) {
            $staff = Role::create(['name' => 'staff']);
            $this->info('Created staff role.');
        }

        if (!$shareholder) {
            $shareholder = Role::create(['name' => 'shareholder']);
            $this->info('Created shareholder role.');
        }

        // 获取或创建权限
        $permissions = [
            'view_users',
            'create_users',
            'edit_users',
            'delete_users',
            'view_credits',
            'create_credits',
            'edit_credits',
            'delete_credits',
            'approve_credits',
        ];

        $this->info('Creating permissions...');
        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
            $this->line("- {$permission}");
        }

        // 为管理员分配所有权限
        $this->info('Assigning permissions to admin...');
        $admin->syncPermissions(Permission::all());

        // 为员工分配特定权限
        $this->info('Assigning permissions to staff...');
        $staffPermissions = Permission::whereIn('name', [
            'view_users',
            'view_credits',
            'create_credits',
        ])->get();
        $staff->syncPermissions($staffPermissions);

        // 为股东分配查看权限和审批权限
        $this->info('Assigning permissions to shareholder...');
        $shareholderPermissions = Permission::whereIn('name', [
            'view_users',
            'view_credits',
            'approve_credits',
        ])->get();
        $shareholder->syncPermissions($shareholderPermissions);

        $this->info('Roles and permissions fixed successfully!');

        return Command::SUCCESS;
    }
}
