<?php

namespace Database\Seeders;

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

/**
 * KnowledgeSharingPermissionSeeder
 *
 * Seeds all permissions required for the Knowledge Sharing module.
 * Includes discussions, replies, knowledge base questions, answers, and categories.
 */
class KnowledgeSharingPermissionSeeder extends Seeder
{
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // ========================================
        // DISCUSSION PERMISSIONS
        // ========================================
        $discussionPermissions = [
            // Discussions
            'view discussions'            => 'View published discussions',
            'create discussions'          => 'Create new discussions',
            'edit discussions'            => 'Edit any discussion',
            'delete discussions'          => 'Delete any discussion',
            'feature discussions'         => 'Mark discussions as featured',
            'pin discussions'             => 'Pin discussions to top',
            'moderate discussions'        => 'Moderate discussion content',
            // Discussion Topics
            'manage discussion topics'    => 'Create, edit, delete discussion topics',
            'create discussion topics'    => 'Create new discussion topics',
            'edit discussion topics'      => 'Edit discussion topics',
            'delete discussion topics'    => 'Delete discussion topics',
            'view discussion topics'      => 'View discussion topics',
            // Discussion Replies
            'manage discussion replies'   => 'Manage all discussion replies',
            'create discussion replies'   => 'Create replies to discussions',
            'edit discussion replies'     => 'Edit any discussion reply',
            'delete discussion replies'   => 'Delete any discussion reply',
            'view discussion replies'     => 'View discussion replies',
        ];

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

        // ========================================
        // KNOWLEDGE BASE PERMISSIONS
        // ========================================
        $knowledgeBasePermissions = [
            // Questions
            'view knowledge base questions'    => 'View knowledge base questions',
            'create knowledge base questions'  => 'Create new knowledge base questions',
            'edit knowledge base questions'    => 'Edit any knowledge base question',
            'delete knowledge base questions'  => 'Delete any knowledge base question',
            'publish knowledge base questions' => 'Publish draft questions',
            'archive knowledge base questions' => 'Archive published questions',
            'feature knowledge base questions' => 'Mark questions as featured',
            // Categories
            'manage knowledge base categories' => 'Create, edit, delete knowledge base categories',
            'create knowledge base categories' => 'Create new knowledge base categories',
            'edit knowledge base categories'   => 'Edit knowledge base categories',
            'delete knowledge base categories' => 'Delete knowledge base categories',
            'view knowledge base categories'   => 'View knowledge base categories',
            // Answers
            'answer knowledge base questions'  => 'Provide answers to questions',
            'edit knowledge base answers'      => 'Edit any knowledge base answer',
            'delete knowledge base answers'    => 'Delete any knowledge base answer',
            'accept knowledge base answers'    => 'Accept answers as correct',
            'moderate knowledge base'          => 'Moderate all knowledge base content',
        ];

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

        // ========================================
        // ASSIGN PERMISSIONS TO ROLES
        // ========================================

        // Super Manager — all permissions (additive)
        $superManager = Role::where('name', 'Super Manager')->first();
        if ($superManager) {
            $superManager->givePermissionTo(array_merge(
                array_keys($discussionPermissions),
                array_keys($knowledgeBasePermissions)
            ));
        }

        // Manager — all except hard-delete of discussions/topics/categories
        $manager = Role::where('name', 'Manager')->first();
        if ($manager) {
            $manager->givePermissionTo([
                // Discussions
                'view discussions',
                'create discussions',
                'edit discussions',
                'delete discussions',
                'feature discussions',
                'pin discussions',
                'moderate discussions',
                // Topics
                'manage discussion topics',
                'create discussion topics',
                'edit discussion topics',
                'delete discussion topics',
                'view discussion topics',
                // Replies
                'manage discussion replies',
                'create discussion replies',
                'edit discussion replies',
                'delete discussion replies',
                'view discussion replies',
                // KB Questions
                'view knowledge base questions',
                'create knowledge base questions',
                'edit knowledge base questions',
                'delete knowledge base questions',
                'publish knowledge base questions',
                'archive knowledge base questions',
                'feature knowledge base questions',
                // KB Categories
                'manage knowledge base categories',
                'create knowledge base categories',
                'edit knowledge base categories',
                'delete knowledge base categories',
                'view knowledge base categories',
                // KB Answers
                'answer knowledge base questions',
                'edit knowledge base answers',
                'delete knowledge base answers',
                'accept knowledge base answers',
                'moderate knowledge base',
            ]);
        }

        // Contributor — can create discussions, replies, and answers
        $contributor = Role::where('name', 'Contributor')->first();
        if ($contributor) {
            $contributor->givePermissionTo([
                'view discussions',
                'create discussions',
                'edit discussions',          // own only (enforced in controller)
                'view discussion topics',
                'create discussion replies',
                'edit discussion replies',   // own only
                'delete discussion replies', // own only
                'view discussion replies',
                'view knowledge base questions',
                'view knowledge base categories',
                'answer knowledge base questions',
                'edit knowledge base answers',   // own only
                'delete knowledge base answers', // own only
            ]);
        }

        // Members — view only
        $members = Role::where('name', 'Members')->first();
        if ($members) {
            $members->givePermissionTo([
                'view discussions',
                'view discussion topics',
                'view discussion replies',
                'view knowledge base questions',
                'view knowledge base categories',
            ]);
        }

        // Trainees — view only
        $trainees = Role::where('name', 'Trainees')->first();
        if ($trainees) {
            $trainees->givePermissionTo([
                'view discussions',
                'view discussion topics',
                'view discussion replies',
                'view knowledge base questions',
                'view knowledge base categories',
            ]);
        }

        $this->command->info('✅ Knowledge Sharing permissions seeded successfully!');
        $this->command->newLine();

        $allPerms = array_merge($discussionPermissions, $knowledgeBasePermissions);
        $this->command->table(
            ['Permission', 'Roles'],
            collect($allPerms)->map(function ($description, $name) {
                $roles = Role::whereHas('permissions', function ($q) use ($name) {
                    $q->where('name', $name);
                })->pluck('name')->join(', ');
                return [$name, $roles ?: 'None'];
            })
        );

        // Clear permission cache
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
    }
}
