<?php

namespace FluxCms\Core\Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class CmsPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->createPermissions();
        $this->createRoles();
    }

    /**
     * Create CMS permissions
     */
    protected function createPermissions(): void
    {
        $permissions = [
            'flux-cms.view' => 'View CMS content',
            'flux-cms.edit' => 'Edit CMS content',
            'flux-cms.publish' => 'Publish CMS content',
            'flux-cms.delete' => 'Delete CMS content',
            'flux-cms.admin' => 'Administer CMS',
        ];

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

        $this->command->info('CMS permissions created successfully!');
    }

    /**
     * Create CMS roles
     */
    protected function createRoles(): void
    {
        // Create CMS Editor role
        $editorRole = Role::firstOrCreate(['name' => 'flux-cms-editor']);
        $editorRole->syncPermissions([
            'flux-cms.view',
            'flux-cms.edit',
        ]);

        // Create CMS Publisher role
        $publisherRole = Role::firstOrCreate(['name' => 'flux-cms-publisher']);
        $publisherRole->syncPermissions([
            'flux-cms.view',
            'flux-cms.edit',
            'flux-cms.publish',
        ]);

        // Create CMS Admin role
        $adminRole = Role::firstOrCreate(['name' => 'flux-cms-admin']);
        $adminRole->syncPermissions([
            'flux-cms.view',
            'flux-cms.edit',
            'flux-cms.publish',
            'flux-cms.delete',
            'flux-cms.admin',
        ]);

        // Create general CMS role (for backward compatibility)
        $cmsRole = Role::firstOrCreate(['name' => 'flux-cms']);
        $cmsRole->syncPermissions([
            'flux-cms.view',
            'flux-cms.edit',
            'flux-cms.publish',
            'flux-cms.delete',
            'flux-cms.admin',
        ]);

        $this->command->info('CMS roles created successfully!');
        $this->command->info('Available roles: flux-cms-editor, flux-cms-publisher, flux-cms-admin, flux-cms');
    }
}
