<?php

namespace Database\Seeders;

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Seeder;

class RolePermissionSeeder extends Seeder
{
    public function run(): void
    {
        // Define a baseline set of permissions aligned with Jetstream's default tokens
        $permissions = collect([
            ['slug' => 'create', 'name' => 'Create'],
            ['slug' => 'read', 'name' => 'Read'],
            ['slug' => 'update', 'name' => 'Update'],
            ['slug' => 'delete', 'name' => 'Delete'],
            ['slug' => 'manage-settings', 'name' => 'Manage Settings'],
            ['slug' => 'manage-imports', 'name' => 'Manage Imports'],
            ['slug' => 'manage-document-templates', 'name' => 'Manage Document Templates'],
        ]);

        $permissions->each(function ($perm) {
            Permission::firstOrCreate(['slug' => $perm['slug']], [
                'name' => $perm['name'],
                'description' => $perm['name'].' permission',
            ]);
        });

        $admin = Role::firstOrCreate(['slug' => 'admin'], [
            'name' => 'Administrator',
            'description' => 'Full access to all features',
        ]);
        $staff = Role::firstOrCreate(['slug' => 'staff'], [
            'name' => 'Staff',
            'description' => 'Standard internal user',
        ]);
        $viewer = Role::firstOrCreate(['slug' => 'viewer'], [
            'name' => 'Viewer',
            'description' => 'Read-only access',
        ]);

        // Attach permissions
        $admin->permissions()->sync(Permission::pluck('id'));
        $staff->permissions()->sync(Permission::whereIn('slug', ['create', 'read', 'update'])->pluck('id'));
        $viewer->permissions()->sync(Permission::where('slug', 'read')->pluck('id'));

        // Ensure specific production emails have the admin role (idempotent)
        $adminEmails = [
            'klara@resovision.com',
        ];

        $adminUserIds = User::whereIn('email', $adminEmails)->pluck('id');
        if ($adminUserIds->isNotEmpty()) {
            // Attach without detaching any existing roles
            $admin->users()->syncWithoutDetaching($adminUserIds->all());
        }
    }
}
