<?php

namespace App\Console\Commands;

use Database\Seeders\PermissionSeeder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncPermissions extends Command
{
    protected $signature = 'permissions:sync';
    protected $description = 'Sync permissions from seeder definition to database and assign new ones to wildcard roles';

    public function handle(): int
    {
        $canonical = PermissionSeeder::getPermissionsList();
        $existing = DB::table('permissions')->pluck('name')->toArray();

        $missing = array_diff($canonical, $existing);

        if (empty($missing)) {
            $this->info('All ' . count($canonical) . ' permissions already exist in the database.');
            return 0;
        }

        $now = now();
        $inserts = [];
        foreach ($missing as $permission) {
            $parts = explode('.', $permission);
            $inserts[] = [
                'name' => $permission,
                'module' => $parts[0],
                'action' => $parts[1] ?? $permission,
                'created_at' => $now,
            ];
        }

        DB::table('permissions')->insert($inserts);
        $this->info('Inserted ' . count($inserts) . ' missing permissions:');
        foreach ($missing as $perm) {
            $this->line("  + {$perm}");
        }

        $newPermIds = DB::table('permissions')
            ->whereIn('name', $missing)
            ->pluck('id')
            ->toArray();

        $wildcardRoles = DB::table('roles')
            ->whereIn('slug', ['super_admin', 'academy_owner'])
            ->pluck('id')
            ->toArray();

        $pivotInserts = [];
        foreach ($wildcardRoles as $roleId) {
            foreach ($newPermIds as $permId) {
                $pivotInserts[] = [
                    'role_id' => $roleId,
                    'permission_id' => $permId,
                    'scope' => 'all',
                    'created_at' => $now,
                ];
            }
        }

        if (!empty($pivotInserts)) {
            foreach (array_chunk($pivotInserts, 100) as $chunk) {
                DB::table('permission_role')->insertOrIgnore($chunk);
            }
            $this->info('Assigned new permissions to ' . count($wildcardRoles) . ' wildcard roles (super_admin, academy_owner).');
        }

        return 0;
    }
}
