<?php

namespace Database\Seeders;

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

class RoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Clear Spatie's permission cache before seeding
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // --- Create Tier Roles ---
        $admin = Role::findOrCreate('admin', 'web');
        Role::findOrCreate('free', 'web');
        Role::findOrCreate('pro', 'web');
        Role::findOrCreate('enterprise', 'web');

        // --- Permissions (admin-only) ---
        $manageMailsPerm = Permission::findOrCreate('manage mails', 'web');
        $managePanelsPerm = Permission::findOrCreate('manage panels', 'web');
        $admin->syncPermissions([$manageMailsPerm, $managePanelsPerm]);

        // --- Migrate legacy 'user' role to 'free' ---
        $legacyRole = Role::where('name', 'user')->where('guard_name', 'web')->first();
        if ($legacyRole) {
            // Move all users with 'user' role to 'free'
            $usersWithLegacyRole = \App\Models\User::role('user')->get();
            foreach ($usersWithLegacyRole as $user) {
                $user->removeRole('user');
                $user->assignRole('free');
            }
            $legacyRole->delete();
        }
    }
}
