<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use BezhanSalleh\FilamentShield\Support\Utils;
use Spatie\Permission\PermissionRegistrar;

class ShieldSeeder extends Seeder
{
    public function run(): void
    {
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $tenants = '[]';
        $users = '[]';
        $userTenantPivot = '[]';
        $rolesWithPermissions = '[{"name":"super_admin","guard_name":"web","permissions":[]},{"name":"ketua","guard_name":"web","permissions":[]},{"name":"bendahara","guard_name":"web","permissions":[]},{"name":"pengurus","guard_name":"web","permissions":[]},{"name":"anggota","guard_name":"web","permissions":[]},{"name":"auditor","guard_name":"web","permissions":[]}]';
        $directPermissions = '[{"name":"ViewAny:Activity","guard_name":"web"},{"name":"View:Activity","guard_name":"web"},{"name":"Create:Activity","guard_name":"web"},{"name":"Update:Activity","guard_name":"web"},{"name":"Delete:Activity","guard_name":"web"},{"name":"DeleteAny:Activity","guard_name":"web"},{"name":"Restore:Activity","guard_name":"web"},{"name":"ForceDelete:Activity","guard_name":"web"},{"name":"ForceDeleteAny:Activity","guard_name":"web"},{"name":"RestoreAny:Activity","guard_name":"web"},{"name":"Replicate:Activity","guard_name":"web"},{"name":"Reorder:Activity","guard_name":"web"},{"name":"ViewAny:Approval","guard_name":"web"},{"name":"View:Approval","guard_name":"web"},{"name":"Create:Approval","guard_name":"web"},{"name":"Update:Approval","guard_name":"web"},{"name":"Delete:Approval","guard_name":"web"},{"name":"DeleteAny:Approval","guard_name":"web"},{"name":"Restore:Approval","guard_name":"web"},{"name":"ForceDelete:Approval","guard_name":"web"},{"name":"ForceDeleteAny:Approval","guard_name":"web"},{"name":"RestoreAny:Approval","guard_name":"web"},{"name":"Replicate:Approval","guard_name":"web"},{"name":"Reorder:Approval","guard_name":"web"},{"name":"ViewAny:Audit","guard_name":"web"},{"name":"View:Audit","guard_name":"web"},{"name":"Create:Audit","guard_name":"web"},{"name":"Update:Audit","guard_name":"web"},{"name":"Delete:Audit","guard_name":"web"},{"name":"DeleteAny:Audit","guard_name":"web"},{"name":"Restore:Audit","guard_name":"web"},{"name":"ForceDelete:Audit","guard_name":"web"},{"name":"ForceDeleteAny:Audit","guard_name":"web"},{"name":"RestoreAny:Audit","guard_name":"web"},{"name":"Replicate:Audit","guard_name":"web"},{"name":"Reorder:Audit","guard_name":"web"},{"name":"ViewAny:CashCategory","guard_name":"web"},{"name":"View:CashCategory","guard_name":"web"},{"name":"Create:CashCategory","guard_name":"web"},{"name":"Update:CashCategory","guard_name":"web"},{"name":"Delete:CashCategory","guard_name":"web"},{"name":"DeleteAny:CashCategory","guard_name":"web"},{"name":"Restore:CashCategory","guard_name":"web"},{"name":"ForceDelete:CashCategory","guard_name":"web"},{"name":"ForceDeleteAny:CashCategory","guard_name":"web"},{"name":"RestoreAny:CashCategory","guard_name":"web"},{"name":"Replicate:CashCategory","guard_name":"web"},{"name":"Reorder:CashCategory","guard_name":"web"},{"name":"ViewAny:CashRecord","guard_name":"web"},{"name":"View:CashRecord","guard_name":"web"},{"name":"Create:CashRecord","guard_name":"web"},{"name":"Update:CashRecord","guard_name":"web"},{"name":"Delete:CashRecord","guard_name":"web"},{"name":"DeleteAny:CashRecord","guard_name":"web"},{"name":"Restore:CashRecord","guard_name":"web"},{"name":"ForceDelete:CashRecord","guard_name":"web"},{"name":"ForceDeleteAny:CashRecord","guard_name":"web"},{"name":"RestoreAny:CashRecord","guard_name":"web"},{"name":"Replicate:CashRecord","guard_name":"web"},{"name":"Reorder:CashRecord","guard_name":"web"},{"name":"ViewAny:ContactMessage","guard_name":"web"},{"name":"View:ContactMessage","guard_name":"web"},{"name":"Create:ContactMessage","guard_name":"web"},{"name":"Update:ContactMessage","guard_name":"web"},{"name":"Delete:ContactMessage","guard_name":"web"},{"name":"DeleteAny:ContactMessage","guard_name":"web"},{"name":"Restore:ContactMessage","guard_name":"web"},{"name":"ForceDelete:ContactMessage","guard_name":"web"},{"name":"ForceDeleteAny:ContactMessage","guard_name":"web"},{"name":"RestoreAny:ContactMessage","guard_name":"web"},{"name":"Replicate:ContactMessage","guard_name":"web"},{"name":"Reorder:ContactMessage","guard_name":"web"},{"name":"ViewAny:Division","guard_name":"web"},{"name":"View:Division","guard_name":"web"},{"name":"Create:Division","guard_name":"web"},{"name":"Update:Division","guard_name":"web"},{"name":"Delete:Division","guard_name":"web"},{"name":"DeleteAny:Division","guard_name":"web"},{"name":"Restore:Division","guard_name":"web"},{"name":"ForceDelete:Division","guard_name":"web"},{"name":"ForceDeleteAny:Division","guard_name":"web"},{"name":"RestoreAny:Division","guard_name":"web"},{"name":"Replicate:Division","guard_name":"web"},{"name":"Reorder:Division","guard_name":"web"},{"name":"ViewAny:MemberDue","guard_name":"web"},{"name":"View:MemberDue","guard_name":"web"},{"name":"Create:MemberDue","guard_name":"web"},{"name":"Update:MemberDue","guard_name":"web"},{"name":"Delete:MemberDue","guard_name":"web"},{"name":"DeleteAny:MemberDue","guard_name":"web"},{"name":"Restore:MemberDue","guard_name":"web"},{"name":"ForceDelete:MemberDue","guard_name":"web"},{"name":"ForceDeleteAny:MemberDue","guard_name":"web"},{"name":"RestoreAny:MemberDue","guard_name":"web"},{"name":"Replicate:MemberDue","guard_name":"web"},{"name":"Reorder:MemberDue","guard_name":"web"},{"name":"ViewAny:Post","guard_name":"web"},{"name":"View:Post","guard_name":"web"},{"name":"Create:Post","guard_name":"web"},{"name":"Update:Post","guard_name":"web"},{"name":"Delete:Post","guard_name":"web"},{"name":"DeleteAny:Post","guard_name":"web"},{"name":"Restore:Post","guard_name":"web"},{"name":"ForceDelete:Post","guard_name":"web"},{"name":"ForceDeleteAny:Post","guard_name":"web"},{"name":"RestoreAny:Post","guard_name":"web"},{"name":"Replicate:Post","guard_name":"web"},{"name":"Reorder:Post","guard_name":"web"},{"name":"ViewAny:User","guard_name":"web"},{"name":"View:User","guard_name":"web"},{"name":"Create:User","guard_name":"web"},{"name":"Update:User","guard_name":"web"},{"name":"Delete:User","guard_name":"web"},{"name":"DeleteAny:User","guard_name":"web"},{"name":"Restore:User","guard_name":"web"},{"name":"ForceDelete:User","guard_name":"web"},{"name":"ForceDeleteAny:User","guard_name":"web"},{"name":"RestoreAny:User","guard_name":"web"},{"name":"Replicate:User","guard_name":"web"},{"name":"Reorder:User","guard_name":"web"},{"name":"ViewAny:Vote","guard_name":"web"},{"name":"View:Vote","guard_name":"web"},{"name":"Create:Vote","guard_name":"web"},{"name":"Update:Vote","guard_name":"web"},{"name":"Delete:Vote","guard_name":"web"},{"name":"DeleteAny:Vote","guard_name":"web"},{"name":"Restore:Vote","guard_name":"web"},{"name":"ForceDelete:Vote","guard_name":"web"},{"name":"ForceDeleteAny:Vote","guard_name":"web"},{"name":"RestoreAny:Vote","guard_name":"web"},{"name":"Replicate:Vote","guard_name":"web"},{"name":"Reorder:Vote","guard_name":"web"},{"name":"ViewAny:Role","guard_name":"web"},{"name":"View:Role","guard_name":"web"},{"name":"Create:Role","guard_name":"web"},{"name":"Update:Role","guard_name":"web"},{"name":"Delete:Role","guard_name":"web"},{"name":"DeleteAny:Role","guard_name":"web"},{"name":"Restore:Role","guard_name":"web"},{"name":"ForceDelete:Role","guard_name":"web"},{"name":"ForceDeleteAny:Role","guard_name":"web"},{"name":"RestoreAny:Role","guard_name":"web"},{"name":"Replicate:Role","guard_name":"web"},{"name":"Reorder:Role","guard_name":"web"},{"name":"View:CashStatsWidget","guard_name":"web"},{"name":"View:StatsOverview","guard_name":"web"},{"name":"View:ActivityLogWidget","guard_name":"web"}]';

        // 1. Seed tenants first (if present)
        if (! blank($tenants) && $tenants !== '[]') {
            static::seedTenants($tenants);
        }

        // 2. Seed roles with permissions
        static::makeRolesWithPermissions($rolesWithPermissions);

        // 3. Seed direct permissions
        static::makeDirectPermissions($directPermissions);

        // 4. Seed users with their roles/permissions (if present)
        if (! blank($users) && $users !== '[]') {
            static::seedUsers($users);
        }

        // 5. Seed user-tenant pivot (if present)
        if (! blank($userTenantPivot) && $userTenantPivot !== '[]') {
            static::seedUserTenantPivot($userTenantPivot);
        }

        $this->command->info('Shield Seeding Completed.');
    }

    protected static function seedTenants(string $tenants): void
    {
        if (blank($tenantData = json_decode($tenants, true))) {
            return;
        }

        $tenantModel = '';
        if (blank($tenantModel)) {
            return;
        }

        foreach ($tenantData as $tenant) {
            $tenantModel::firstOrCreate(
                ['id' => $tenant['id']],
                $tenant
            );
        }
    }

    protected static function seedUsers(string $users): void
    {
        if (blank($userData = json_decode($users, true))) {
            return;
        }

        $userModel = 'App\Models\User';
        $tenancyEnabled = false;

        foreach ($userData as $data) {
            // Extract role/permission data before creating user
            $roles = $data['roles'] ?? [];
            $permissions = $data['permissions'] ?? [];
            $tenantRoles = $data['tenant_roles'] ?? [];
            $tenantPermissions = $data['tenant_permissions'] ?? [];
            unset($data['roles'], $data['permissions'], $data['tenant_roles'], $data['tenant_permissions']);

            $user = $userModel::firstOrCreate(
                ['email' => $data['email']],
                $data
            );

            // Handle tenancy mode - sync roles/permissions per tenant
            if ($tenancyEnabled && (! empty($tenantRoles) || ! empty($tenantPermissions))) {
                foreach ($tenantRoles as $tenantId => $roleNames) {
                    $contextId = $tenantId === '_global' ? null : $tenantId;
                    setPermissionsTeamId($contextId);
                    $user->syncRoles($roleNames);
                }

                foreach ($tenantPermissions as $tenantId => $permissionNames) {
                    $contextId = $tenantId === '_global' ? null : $tenantId;
                    setPermissionsTeamId($contextId);
                    $user->syncPermissions($permissionNames);
                }
            } else {
                // Non-tenancy mode
                if (! empty($roles)) {
                    $user->syncRoles($roles);
                }

                if (! empty($permissions)) {
                    $user->syncPermissions($permissions);
                }
            }
        }
    }

    protected static function seedUserTenantPivot(string $pivot): void
    {
        if (blank($pivotData = json_decode($pivot, true))) {
            return;
        }

        $pivotTable = '';
        if (blank($pivotTable)) {
            return;
        }

        foreach ($pivotData as $row) {
            $uniqueKeys = [];

            if (isset($row['user_id'])) {
                $uniqueKeys['user_id'] = $row['user_id'];
            }

            $tenantForeignKey = 'team_id';
            if (! blank($tenantForeignKey) && isset($row[$tenantForeignKey])) {
                $uniqueKeys[$tenantForeignKey] = $row[$tenantForeignKey];
            }

            if (! empty($uniqueKeys)) {
                DB::table($pivotTable)->updateOrInsert($uniqueKeys, $row);
            }
        }
    }

    protected static function makeRolesWithPermissions(string $rolesWithPermissions): void
    {
        if (blank($rolePlusPermissions = json_decode($rolesWithPermissions, true))) {
            return;
        }

        /** @var \Illuminate\Database\Eloquent\Model $roleModel */
        $roleModel = Utils::getRoleModel();
        /** @var \Illuminate\Database\Eloquent\Model $permissionModel */
        $permissionModel = Utils::getPermissionModel();

        $tenancyEnabled = false;
        $teamForeignKey = 'team_id';

        foreach ($rolePlusPermissions as $rolePlusPermission) {
            $tenantId = $rolePlusPermission[$teamForeignKey] ?? null;

            // Set tenant context for role creation and permission sync
            if ($tenancyEnabled) {
                setPermissionsTeamId($tenantId);
            }

            $roleData = [
                'name' => $rolePlusPermission['name'],
                'guard_name' => $rolePlusPermission['guard_name'],
            ];

            // Include tenant ID in role data (can be null for global roles)
            if ($tenancyEnabled && ! blank($teamForeignKey)) {
                $roleData[$teamForeignKey] = $tenantId;
            }

            $role = $roleModel::firstOrCreate($roleData);

            if (! blank($rolePlusPermission['permissions'])) {
                $permissionModels = collect($rolePlusPermission['permissions'])
                    ->map(fn ($permission) => $permissionModel::firstOrCreate([
                        'name' => $permission,
                        'guard_name' => $rolePlusPermission['guard_name'],
                    ]))
                    ->all();

                $role->syncPermissions($permissionModels);
            }
        }
    }

    public static function makeDirectPermissions(string $directPermissions): void
    {
        if (blank($permissions = json_decode($directPermissions, true))) {
            return;
        }

        /** @var \Illuminate\Database\Eloquent\Model $permissionModel */
        $permissionModel = Utils::getPermissionModel();

        foreach ($permissions as $permission) {
            if ($permissionModel::whereName($permission['name'])->doesntExist()) {
                $permissionModel::create([
                    'name' => $permission['name'],
                    'guard_name' => $permission['guard_name'],
                ]);
            }
        }
    }
}
