<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

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

        foreach (config('poskn.roles', []) as $name) {
            Role::query()->firstOrCreate(
                ['name' => $name, 'guard_name' => 'web']
            );
        }

        $this->migrateLegacyUserRoles();
        $this->deleteLegacyRoles();
    }

    /**
     * Convierte asignaciones de la convención anterior a los 4 roles actuales.
     */
    protected function migrateLegacyUserRoles(): void
    {
        $legacyPriority = ['super_admin', 'admin', 'doctor', 'reception', 'pharmacy'];

        $map = [
            'super_admin' => 'administrador',
            'admin' => 'gerente',
            'doctor' => 'medico',
            'reception' => 'cajero',
            'pharmacy' => 'cajero',
        ];

        foreach (User::query()->with('roles')->cursor() as $user) {
            $oldNames = $user->roles->pluck('name')->all();
            $chosenLegacy = null;
            foreach ($legacyPriority as $legacy) {
                if (in_array($legacy, $oldNames, true)) {
                    $chosenLegacy = $legacy;
                    break;
                }
            }
            if ($chosenLegacy !== null && isset($map[$chosenLegacy])) {
                $user->syncRoles([$map[$chosenLegacy]]);
            }
        }
    }

    protected function deleteLegacyRoles(): void
    {
        $legacy = ['super_admin', 'admin', 'doctor', 'reception', 'pharmacy'];

        Role::query()
            ->where('guard_name', 'web')
            ->whereIn('name', $legacy)
            ->delete();
    }
}
