<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PermissionSeeder extends Seeder
{
    public function run(): void
    {
        $permissions = [
            // Dashboard
            'dashboard.view', 'dashboard.export',

            // Organizations
            'academies.list', 'academies.show', 'academies.update',
            'branches.list', 'branches.create', 'branches.update', 'branches.delete',

            // Identity & Users
            'users.list', 'users.create', 'users.update', 'users.delete', 'users.assign_roles',
            'roles.list', 'roles.create', 'roles.update', 'roles.delete', 'roles.assign_permissions',
            'people.list', 'people.create', 'people.update', 'people.delete', 'people.merge',

            // Participants
            'participants.list', 'participants.create', 'participants.update', 'participants.delete',
            'participants.show', 'participants.change_status', 'participants.export',
            'participants.view_financial', 'participants.view_attendance',
            'guardians.list', 'guardians.create', 'guardians.update',

            // Training
            'activities.list', 'activities.create', 'activities.update', 'activities.delete',
            'programs.list', 'programs.create', 'programs.update', 'programs.delete', 'programs.show',
            'groups.list', 'groups.create', 'groups.update', 'groups.delete', 'groups.show',
            'groups.manage_enrollments',
            'sessions.list', 'sessions.show', 'sessions.cancel', 'sessions.reschedule',
            'sessions.start', 'sessions.complete', 'sessions.generate',
            'schedules.list', 'schedules.manage',
            'enrollments.list', 'enrollments.create', 'enrollments.cancel',
            'enrollments.override', 'enrollments.transfer',
            'holidays.list', 'holidays.create', 'holidays.update', 'holidays.delete',
            'waitlists.manage', 'waitlists.promote',

            // Attendance
            'attendance.list', 'attendance.mark', 'attendance.edit', 'attendance.export',
            'attendance.view_reports',
            'excuses.list', 'excuses.submit', 'excuses.approve', 'excuses.reject',

            // Financial
            'invoices.list', 'invoices.create', 'invoices.update', 'invoices.cancel',
            'invoices.show', 'invoices.send', 'invoices.export',
            'payments.list', 'payments.create', 'payments.refund', 'payments.export',
            'transactions.list', 'transactions.export',
            'accounts.list', 'accounts.create', 'accounts.update',
            'wallets.list', 'wallets.credit', 'wallets.debit', 'wallets.freeze',
            'payment_plans.list', 'payment_plans.create', 'payment_plans.update',
            'cash_sessions.open', 'cash_sessions.close', 'cash_sessions.list',
            'refunds.initiate', 'refunds.approve',
            'daily_closing.create', 'daily_closing.view',

            // Pricing
            'pricing.list', 'pricing.create', 'pricing.update', 'pricing.delete',
            'base_prices.list', 'base_prices.manage',
            'pricing_rules.list', 'pricing_rules.manage',
            'promotions.list', 'promotions.create', 'promotions.update', 'promotions.delete',
            'coupons.list', 'coupons.generate', 'coupons.deactivate',

            // POS
            'pos.access', 'pos.override_price', 'pos.override_stock', 'pos.void_transaction',
            'pos_sessions.open', 'pos_sessions.close', 'pos_sessions.list',

            // Inventory
            'products.list', 'products.create', 'products.update', 'products.delete', 'products.export',
            'categories.list', 'categories.manage',
            'warehouses.list', 'warehouses.create', 'warehouses.update',
            'inventory.view_levels', 'inventory.adjust', 'inventory.transfer',
            'purchase_orders.list', 'purchase_orders.create', 'purchase_orders.approve', 'purchase_orders.receive',
            'stock_counts.list', 'stock_counts.create', 'stock_counts.approve',
            'kits.list', 'kits.create', 'kits.update', 'kits.delete',
            'suppliers.list', 'suppliers.create', 'suppliers.update',

            // Facilities
            'facilities.list', 'facilities.create', 'facilities.update', 'facilities.delete', 'facilities.show',
            'facilities.manage_layouts', 'facilities.manage_hours',
            'reservations.list', 'reservations.create', 'reservations.cancel', 'reservations.confirm',

            // Assignments
            'assignments.list', 'assignments.create', 'assignments.update', 'assignments.cancel',

            // Notifications
            'notifications.send', 'notifications.manage_templates',
            'notification_preferences.manage',

            // Reports
            'reports.financial', 'reports.attendance', 'reports.enrollment',
            'reports.inventory', 'reports.trainer', 'reports.facility',
            'reports.export_pdf', 'reports.export_excel',

            // Approvals
            'approvals.list', 'approvals.approve', 'approvals.reject', 'approvals.configure',

            // Settings
            'settings.manage', 'settings.view', 'settings.view_audit_log',

            // Evaluations
            'evaluations.list', 'evaluations.create', 'evaluations.update', 'evaluations.manage',

            // Audit
            'audit.list', 'audit.export',

            // POS (route-aligned aliases)
            'pos.sell', 'pos.list',

            // Notifications (route-aligned)
            'notifications.manage',

            // Cash Sessions (route-aligned)
            'cash_sessions.manage',

            // Wallets (route-aligned)
            'wallets.view',

            // Inventory (route-aligned)
            'inventory.list', 'inventory.create', 'inventory.update',

            // Reports (route-aligned)
            'reports.view',

            // Super Admin
            'super_admin.access',
        ];

        // Insert permissions (idempotent)
        $now = now();
        foreach ($permissions as $permission) {
            $parts = explode('.', $permission);
            DB::table('permissions')->updateOrInsert(
                ['name' => $permission],
                [
                    'name' => $permission,
                    'module' => $parts[0],
                    'action' => $parts[1] ?? $permission,
                    'created_at' => $now,
                ]
            );
        }

        $this->command->info('Seeded ' . count($permissions) . ' permissions.');

        // Role → Permission mapping
        $rolePermissions = $this->getRolePermissions($permissions);

        foreach ($rolePermissions as $roleSlug => $perms) {
            $role = DB::table('roles')->where('slug', $roleSlug)->first();
            if (!$role) {
                continue;
            }

            if ($perms === '*') {
                $permIds = DB::table('permissions')->pluck('id')->toArray();
            } else {
                $permIds = DB::table('permissions')->whereIn('name', $perms)->pluck('id')->toArray();
            }

            // Sync: remove old, insert new
            DB::table('permission_role')->where('role_id', $role->id)->delete();
            $scope = in_array($roleSlug, ['super_admin', 'academy_owner', 'academy_admin']) ? 'all' : 'academy';
            $inserts = array_map(fn ($pid) => [
                'role_id' => $role->id,
                'permission_id' => $pid,
                'scope' => $scope,
                'created_at' => $now,
            ], $permIds);
            foreach (array_chunk($inserts, 100) as $chunk) {
                DB::table('permission_role')->insert($chunk);
            }

            $this->command->info("  Role '{$roleSlug}': " . count($permIds) . ' permissions assigned.');
        }
    }

    private function getRolePermissions(array $allPermissions): array
    {
        return [
            'super_admin' => '*',
            'academy_owner' => '*',
            'academy_admin' => array_filter($allPermissions, fn ($p) => !in_array($p, [
                'settings.manage', 'roles.delete',
            ])),
            'branch_manager' => array_filter($allPermissions, fn ($p) =>
                str_starts_with($p, 'participants.') ||
                str_starts_with($p, 'guardians.') ||
                str_starts_with($p, 'activities.') ||
                str_starts_with($p, 'programs.') ||
                str_starts_with($p, 'groups.') ||
                str_starts_with($p, 'sessions.') ||
                str_starts_with($p, 'schedules.') ||
                str_starts_with($p, 'enrollments.') ||
                str_starts_with($p, 'attendance.') ||
                str_starts_with($p, 'excuses.') ||
                str_starts_with($p, 'invoices.') ||
                str_starts_with($p, 'payments.') ||
                str_starts_with($p, 'wallets.') ||
                str_starts_with($p, 'cash_sessions.') ||
                str_starts_with($p, 'pricing.') ||
                str_starts_with($p, 'pos.') ||
                str_starts_with($p, 'inventory.') ||
                str_starts_with($p, 'products.') ||
                str_starts_with($p, 'warehouses.') ||
                str_starts_with($p, 'facilities.') ||
                str_starts_with($p, 'reservations.') ||
                str_starts_with($p, 'assignments.') ||
                str_starts_with($p, 'evaluations.') ||
                str_starts_with($p, 'notifications.') ||
                str_starts_with($p, 'reports.') ||
                str_starts_with($p, 'audit.') ||
                $p === 'dashboard.view' || $p === 'holidays.list' ||
                $p === 'settings.view'
            ),
            'head_trainer' => [
                'dashboard.view',
                'sessions.list', 'sessions.show', 'sessions.start', 'sessions.complete',
                'sessions.cancel', 'sessions.reschedule', 'sessions.generate',
                'schedules.list', 'schedules.manage',
                'attendance.list', 'attendance.mark', 'attendance.edit', 'attendance.view_reports',
                'groups.list', 'groups.show',
                'evaluations.list', 'evaluations.create', 'evaluations.update',
                'participants.list', 'participants.show', 'participants.view_attendance',
                'excuses.list', 'excuses.approve', 'excuses.reject',
                'assignments.list',
            ],
            'trainer' => [
                'dashboard.view',
                'sessions.list', 'sessions.show', 'sessions.start', 'sessions.complete',
                'attendance.list', 'attendance.mark',
                'groups.list', 'groups.show',
                'evaluations.list', 'evaluations.create',
                'participants.list', 'participants.show',
            ],
            'receptionist' => [
                'dashboard.view',
                'participants.list', 'participants.show', 'participants.create',
                'guardians.list', 'guardians.create',
                'enrollments.create',
                'pos.access', 'pos.sell', 'pos.list',
                'invoices.show',
                'payments.create',
                'cash_sessions.open', 'cash_sessions.close', 'cash_sessions.list',
            ],
            'accountant' => [
                'dashboard.view',
                'invoices.list', 'invoices.create', 'invoices.update', 'invoices.cancel',
                'invoices.show', 'invoices.send', 'invoices.export',
                'payments.list', 'payments.create', 'payments.refund', 'payments.export',
                'transactions.list', 'transactions.export',
                'accounts.list', 'accounts.create', 'accounts.update',
                'wallets.list', 'wallets.view', 'wallets.credit', 'wallets.debit', 'wallets.freeze',
                'payment_plans.list', 'payment_plans.create', 'payment_plans.update',
                'cash_sessions.open', 'cash_sessions.close', 'cash_sessions.list', 'cash_sessions.manage',
                'refunds.initiate', 'refunds.approve',
                'daily_closing.create', 'daily_closing.view',
                'reports.financial', 'reports.view', 'reports.export_pdf', 'reports.export_excel',
                'pricing.list',
            ],
            'data_entry' => [
                'dashboard.view',
                'participants.list', 'participants.create', 'participants.update',
                'guardians.list', 'guardians.create', 'guardians.update',
                'people.list', 'people.create', 'people.update',
            ],
            'parent' => [
                'dashboard.view',
                'attendance.list',
            ],
        ];
    }
}
