<?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;

class MembershipPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Define all permissions for the Membership Management Module
        $permissions = [
            // Member Management
            'view members',
            'create members',
            'edit members',
            'delete members',
            'approve members',
            
            // Membership Categories
            'view membership categories',
            'create membership categories',
            'edit membership categories',
            'delete membership categories',
            
            // Subscription Fees
            'view subscription fees',
            'create subscription fees',
            'edit subscription fees',
            'delete subscription fees',
            
            // Contribution Fees
            'view contribution fees',
            'create contribution fees',
            'edit contribution fees',
            'delete contribution fees',
            
            // Contributions
            'view contributions',
            'create contributions',
            'edit contributions',
            'delete contributions',
            'export contributions',
            
            // Loan Products
            'view loan products',
            'create loan products',
            'edit loan products',
            'delete loan products',
            
            // Loan Applications
            'view loan applications',
            'approve loan applications',
            'reject loan applications',
            'disburse loans',
            'verify loan documents',
            
            // Payment & Transactions
            'view transactions',
            'process payments',
            'refund payments',
            
            // Reports
            'view reports',
            'export reports',

            // Membership Certificates & Renewals
            'view membership certificate',
            'renew membership',
            'view renewal history',
            'manage renewal configs',
            'issue membership certificates',
        ];

        // Create all permissions
        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
        }

        // Define role-permission mappings
        $rolePermissions = [
            'Super Manager' => $permissions, // All permissions
            
            'Manager' => [
                'view members',
                'create members',
                'edit members',
                'approve members',
                'view membership categories',
                'view subscription fees',
                'view contribution fees',
                'view contributions',
                'create contributions',
                'edit contributions',
                'export contributions',
                'view loan products',
                'create loan products',
                'edit loan products',
                'view loan applications',
                'approve loan applications',
                'reject loan applications',
                'disburse loans',
                'verify loan documents',
                'view transactions',
                'view reports',
                'export reports',
                'view membership certificate',
                'view renewal history',
                'manage renewal configs',
                'issue membership certificates',
            ],
            
            'Members' => [
                'view contributions',
                'view loan products',
                'view membership certificate',
                'renew membership',
                'view renewal history',
            ],
            
            'Trainers' => [
                'view members',
                'view contributions',
            ],
            
            'Trainees' => [
                'view contributions',
            ],
            
            'Mentor' => [
                'view members',
                'view contributions',
            ],
            
            'Mentee' => [
                'view contributions',
            ],
            
            'Partners' => [
                'view members',
                'view contributions',
                'view reports',
            ],
            
            'Contributor' => [
                'view members',
                'view contributions',
                'view loan products',
            ],
            
            'Health Marketor' => [
                'view members',
                'view reports',
                'export reports',
            ],
        ];

        // Create roles and assign permissions (additive — do not sync/overwrite)
        foreach ($rolePermissions as $roleName => $perms) {
            $role = Role::firstOrCreate(['name' => $roleName]);
            $role->givePermissionTo($perms);
        }

        $this->command->info('Membership module permissions seeded successfully!');

        // Optionally create a test super manager
        if (app()->environment('local', 'development', 'testing')) {
            $this->createTestUsers();
        }

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

    /**
     * Create test users for development.
     */
    protected function createTestUsers(): void
    {
        // Super Manager
        $superManager = User::firstOrCreate(
            ['email' => 'superadmin@membership.test'],
            [
                'name'               => 'Super Manager',
                'username'           => 'superadmin.membership',
                'password'           => Hash::make('password'),
                'email_verified_at'  => now(),
                'is_active'          => true,
            ]
        );
        $superManager->assignRole('Super Manager');

        // Manager
        $manager = User::firstOrCreate(
            ['email' => 'manager@membership.test'],
            [
                'name'               => 'Test Manager',
                'username'           => 'manager.membership',
                'password'           => Hash::make('password'),
                'email_verified_at'  => now(),
                'is_active'          => true,
            ]
        );
        $manager->assignRole('Manager');

        // Member
        $member = User::firstOrCreate(
            ['email' => 'member@membership.test'],
            [
                'name'               => 'Test Member',
                'username'           => 'member.membership',
                'password'           => Hash::make('password'),
                'email_verified_at'  => now(),
                'is_active'          => true,
            ]
        );
        $member->assignRole('Members');

        $this->command->info('Test users created:');
        $this->command->info('- superadmin@membership.test (Super Manager)');
        $this->command->info('- manager@membership.test (Manager)');
        $this->command->info('- member@membership.test (Member)');
        $this->command->info('Password for all: password');
    }
}
