<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

/**
 * HealthDirectoryPermissionSeeder
 *
 * Creates roles and permissions for the Health Directory Marketing Platform.
 * Integrates with existing Spatie Laravel Permission system.
 *
 * Roles Created:
 * - Health Marketor: Can manage their own institutions and machines
 * - Manager: Can approve/reject listings and manage publishing pages
 * - Super Manager: Full administrative access
 *
 * Requirements: 8.1, 8.2
 */
class HealthDirectoryPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // =====================================================================
        // CREATE PERMISSIONS
        // =====================================================================

        // --- Institution Permissions ---
        $institutionPermissions = [
            'view institutions' => 'View health institution listings',
            'create institutions' => 'Register new health institutions',
            'edit institutions' => 'Edit institution details',
            'delete institutions' => 'Delete institution listings',
            'manage institutions' => 'Manage all institution listings (admin)',
            'approve institutions' => 'Approve or reject institution listings',
        ];

        // --- Machine Permissions ---
        $machinePermissions = [
            'view machines' => 'View digital machine listings',
            'create machines' => 'Add new machine listings',
            'edit machines' => 'Edit machine details',
            'delete machines' => 'Delete machine listings',
            'manage machines' => 'Manage all machine listings (admin)',
            'approve machines' => 'Approve or reject machine listings',
        ];

        // --- Publishing Permissions ---
        $publishingPermissions = [
            'view pages' => 'View publishing pages',
            'create pages' => 'Create new publishing pages',
            'edit pages' => 'Edit publishing pages',
            'delete pages' => 'Delete publishing pages',
            'manage pages' => 'Manage all publishing pages (admin)',
        ];

        // --- Payment Permissions ---
        $paymentPermissions = [
            'view payments' => 'View payment history',
            'manage payments' => 'Manage payment records (admin)',
            'configure payments' => 'Configure payment settings',
        ];

        // --- Dashboard Permissions ---
        $dashboardPermissions = [
            'view marketor dashboard' => 'Access Health Marketor dashboard',
            'view admin dashboard' => 'Access administrative dashboard',
            'view statistics' => 'View statistics and reports',
        ];

        // Combine all permissions
        $allPermissions = array_merge(
            $institutionPermissions,
            $machinePermissions,
            $publishingPermissions,
            $paymentPermissions,
            $dashboardPermissions
        );

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

        $this->command->info('Permissions created successfully.');


        // =====================================================================
        // CREATE ROLES
        // =====================================================================

        // --- Health Marketor Role ---
        $healthMarketor = Role::firstOrCreate(
            ['name' => 'Health Marketor', 'guard_name' => 'web'],
            ['theme' => 'red']
        );

        $healthMarketor->givePermissionTo([
            'view institutions',
            'create institutions',
            'edit institutions',
            'view machines',
            'create machines',
            'edit machines',
            'delete machines',
            'view payments',
            'view marketor dashboard',
        ]);

        $this->command->info('Health Marketor role created with permissions.');


        // --- Manager Role ---
        $manager = Role::firstOrCreate(
            ['name' => 'Manager', 'guard_name' => 'web'],
            ['theme' => 'blue']
        );

        $manager->givePermissionTo([
            // Institution permissions
            'view institutions',
            'create institutions',
            'edit institutions',
            'delete institutions',
            'manage institutions',
            'approve institutions',
            
            // Machine permissions
            'view machines',
            'create machines',
            'edit machines',
            'delete machines',
            'manage machines',
            'approve machines',
            
            // Publishing permissions
            'view pages',
            'create pages',
            'edit pages',
            'delete pages',
            'manage pages',
            
            // Payment permissions
            'view payments',
            'manage payments',
            'configure payments',
            
            // Dashboard permissions
            'view marketor dashboard',
            'view admin dashboard',
            'view statistics',
        ]);

        $this->command->info('Manager role created with permissions.');


        // --- Super Manager Role ---
        $superManager = Role::firstOrCreate(
            ['name' => 'Super Manager', 'guard_name' => 'web'],
            ['theme' => 'dark']
        );

        // Super Manager gets all permissions
        $superManager->givePermissionTo(Permission::all());

        $this->command->info('Super Manager role created with all permissions.');


        // =====================================================================
        // UPDATE EXISTING ROLES IF NEEDED
        // =====================================================================

        // Give Health Marketor permissions to existing Members role (optional)
        $members = Role::where('name', 'Members')->first();
        if ($members) {
            $members->givePermissionTo([
                'view institutions',
                'view machines',
            ]);
            $this->command->info('Members role updated with viewing permissions.');
        }

        // Give Manager permissions to existing Partners role (optional)
        $partners = Role::where('name', 'Partners')->first();
        if ($partners) {
            $partners->givePermissionTo([
                'view institutions',
                'view machines',
                'view pages',
            ]);
            $this->command->info('Partners role updated with viewing permissions.');
        }


        // =====================================================================
        // CREATE TEST USERS (Optional - for development)
        // =====================================================================

        if (app()->environment('local', 'development', 'staging')) {

            // Create test Health Marketor
            $marketor = User::firstOrCreate(
                ['email' => 'marketor@healthdirectory.test'],
                [
                    'name'               => 'Test Health Marketor',
                    'username'           => 'marketor.healthdir',
                    'password'           => Hash::make('password'),
                    'email_verified_at'  => now(),
                    'is_active'          => true,
                ]
            );
            $marketor->assignRole('Health Marketor');
            $this->command->info('Test Health Marketor created: marketor@healthdirectory.test / password');

            // Create test Manager
            $managerUser = User::firstOrCreate(
                ['email' => 'manager@healthdirectory.test'],
                [
                    'name'               => 'Test Manager',
                    'username'           => 'manager.healthdir',
                    'password'           => Hash::make('password'),
                    'email_verified_at'  => now(),
                    'is_active'          => true,
                ]
            );
            $managerUser->assignRole('Manager');
            $this->command->info('Test Manager created: manager@healthdirectory.test / password');

            // Create test Super Manager
            $superManagerUser = User::firstOrCreate(
                ['email' => 'supermanager@healthdirectory.test'],
                [
                    'name'               => 'Test Super Manager',
                    'username'           => 'supermanager.healthdir',
                    'password'           => Hash::make('password'),
                    'email_verified_at'  => now(),
                    'is_active'          => true,
                ]
            );
            $superManagerUser->assignRole('Super Manager');
            $this->command->info('Test Super Manager created: supermanager@healthdirectory.test / password');
        }


        // =====================================================================
        // SUMMARY
        // =====================================================================

        $this->command->newLine();
        $this->command->info('==========================================');
        $this->command->info('Health Directory Permission Seeder Complete');
        $this->command->info('==========================================');
        $this->command->newLine();
        $this->command->table(
            ['Role', 'Permissions Count', 'Theme'],
            [
                ['Health Marketor', $healthMarketor->permissions->count(), $healthMarketor->theme ?? 'red'],
                ['Manager', $manager->permissions->count(), $manager->theme ?? 'blue'],
                ['Super Manager', $superManager->permissions->count(), $superManager->theme ?? 'dark'],
            ]
        );
        $this->command->newLine();
        $this->command->info('Total permissions created: ' . Permission::count());
        $this->command->newLine();

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