<?php

namespace Database\Seeders;

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

class CommunicationPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * This seeder creates all permissions for the Communication Module
     * and assigns them to the appropriate roles.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // ============================================
        // TICKETING SYSTEM PERMISSIONS
        // ============================================
        $ticketPermissions = [
            'view tickets' => 'View ticket listing and details',
            'create tickets' => 'Create new support tickets',
            'edit tickets' => 'Edit existing tickets',
            'delete tickets' => 'Delete tickets (Manager/Super Manager only)',
            'reply tickets' => 'Add replies to ticket conversations',
            'assign tickets' => 'Assign tickets to agents',
            'manage ticket categories' => 'Manage ticket categories',
        ];

        // ============================================
        // SMS SYSTEM PERMISSIONS
        // ============================================
        $smsPermissions = [
            'view sms' => 'View SMS history and dashboard',
            'create sms' => 'Compose and send SMS messages',
            'delete sms' => 'Delete SMS history records',
            'manage sms templates' => 'Create, edit, and delete SMS templates',
            'view sms statistics' => 'View SMS statistics and reports',
        ];

        // ============================================
        // EMAIL SYSTEM PERMISSIONS
        // ============================================
        $emailPermissions = [
            'view emails' => 'View email history and dashboard',
            'create emails' => 'Compose and send email messages',
            'delete emails' => 'Delete email history records',
            'reply emails' => 'Reply to received emails',
            'manage email templates' => 'Create, edit, and delete email templates',
            'view email statistics' => 'View email statistics and reports',
        ];

        // ============================================
        // CHAT SYSTEM PERMISSIONS
        // ============================================
        $chatPermissions = [
            'view chats'           => 'View chat dashboard and statistics',
            'handle chats'         => 'Handle chat conversations as agent',
            'manage chat categories' => 'Create, edit, and delete chat categories',
            'appoint chat agents'  => 'Appoint and remove chat agents',
            'view chat statistics' => 'View detailed chat statistics',
        ];

        // ============================================
        // CREATE ALL PERMISSIONS
        // ============================================
        $allPermissions = array_merge(
            $ticketPermissions,
            $smsPermissions,
            $emailPermissions,
            $chatPermissions
        );

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

        $this->command->info('Created ' . count($allPermissions) . ' communication permissions.');

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

        // Super Manager - Full access
        $superManager = Role::where('name', 'Super Manager')->first();
        if ($superManager) {
            $superManager->givePermissionTo(array_keys($allPermissions));
            $this->command->info('Super Manager: All permissions assigned.');
        }

        // Manager - Most permissions except some deletions
        $manager = Role::where('name', 'Manager')->first();
        if ($manager) {
            $managerPermissions = [
                // Tickets
                'view tickets', 'create tickets', 'edit tickets', 'delete tickets',
                'reply tickets', 'assign tickets', 'manage ticket categories',
                // SMS
                'view sms', 'create sms', 'delete sms', 'manage sms templates',
                'view sms statistics',
                // Email
                'view emails', 'create emails', 'delete emails', 'reply emails',
                'manage email templates', 'view email statistics',
                // Chat
                'view chats', 'handle chats', 'manage chat categories',
                'appoint chat agents', 'view chat statistics',
            ];
            $manager->givePermissionTo($managerPermissions);
            $this->command->info('Manager: ' . count($managerPermissions) . ' permissions assigned.');
        }

        // Members - Basic ticket and limited communication
        $members = Role::where('name', 'Members')->first();
        if ($members) {
            $membersPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
            ];
            $members->givePermissionTo($membersPermissions);
            $this->command->info('Members: ' . count($membersPermissions) . ' permissions assigned.');
        }

        // Trainers - Can communicate with Trainees only
        $trainers = Role::where('name', 'Trainers')->first();
        if ($trainers) {
            $trainersPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
                'view sms', 'create sms',
                'view emails', 'create emails',
            ];
            $trainers->givePermissionTo($trainersPermissions);
            $this->command->info('Trainers: ' . count($trainersPermissions) . ' permissions assigned.');
        }

        // Trainees - Can create tickets only
        $trainees = Role::where('name', 'Trainees')->first();
        if ($trainees) {
            $traineesPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
            ];
            $trainees->givePermissionTo($traineesPermissions);
            $this->command->info('Trainees: ' . count($traineesPermissions) . ' permissions assigned.');
        }

        // Mentors - Can communicate with Mentees only
        $mentor = Role::where('name', 'Mentor')->first();
        if ($mentor) {
            $mentorPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
                'view sms', 'create sms',
                'view emails', 'create emails',
            ];
            $mentor->givePermissionTo($mentorPermissions);
            $this->command->info('Mentor: ' . count($mentorPermissions) . ' permissions assigned.');
        }

        // Mentee - Can create tickets only
        $mentee = Role::where('name', 'Mentee')->first();
        if ($mentee) {
            $menteePermissions = [
                'view tickets', 'create tickets', 'reply tickets',
            ];
            $mentee->givePermissionTo($menteePermissions);
            $this->command->info('Mentee: ' . count($menteePermissions) . ' permissions assigned.');
        }

        // Partners - Basic access
        $partners = Role::where('name', 'Partners')->first();
        if ($partners) {
            $partnersPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
            ];
            $partners->givePermissionTo($partnersPermissions);
            $this->command->info('Partners: ' . count($partnersPermissions) . ' permissions assigned.');
        }

        // Contributors - Basic access
        $contributor = Role::where('name', 'Contributor')->first();
        if ($contributor) {
            $contributorPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
            ];
            $contributor->givePermissionTo($contributorPermissions);
            $this->command->info('Contributor: ' . count($contributorPermissions) . ' permissions assigned.');
        }

        // Health Marketer - Basic access
        $healthMarketer = Role::where('name', 'Health Marketor')->first();
        if ($healthMarketer) {
            $healthMarketerPermissions = [
                'view tickets', 'create tickets', 'reply tickets',
                'view sms', 'create sms',
                'view emails', 'create emails',
            ];
            $healthMarketer->givePermissionTo($healthMarketerPermissions);
            $this->command->info('Health Marketor: ' . count($healthMarketerPermissions) . ' permissions assigned.');
        }

        $this->command->newLine();
        $this->command->info('============================================');
        $this->command->info('Communication Module Permissions Seeded!');
        $this->command->info('============================================');

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