<?php

namespace Database\Seeders;

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

class UserFixSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 1. Cập nhật user Admin (ID=1)
        $admin = User::find(1);
        if ($admin) {
            $admin->update([
                'name'              => 'Admin',
                'email'             => 'admin@admin.dev',
                'password'          => Hash::make('abc1234$'),
                'email_verified_at' => now(),
            ]);
            $this->command->info('Admin user (ID=1) đã được cập nhật.');
        } else {
            $admin = User::create([
                'name'              => 'Admin',
                'email'             => 'admin@admin.dev',
                'password'          => Hash::make('abc1234$'),
                'email_verified_at' => now(),
            ]);
            $this->command->info('Admin user mới đã được tạo với ID: ' . $admin->id);
        }

        // 2. Đổi mật khẩu cho tất cả users
        User::query()->update(['password' => Hash::make('abc1234$')]);
        $this->command->info('Đã đổi mật khẩu cho tất cả ' . User::count() . ' users thành: abc1234$');

        // 3. Tạo user cho từng role nếu chưa có
        $roles = ['administrator', 'editor', 'contributor', 'author', 'subscriber', 'expert', 'user', 'company', 'group', 'freelancer'];

        foreach ($roles as $roleName) {
            $role = Role::where('name', $roleName)->exists();
            if (! $role) {
                Role::create(['name' => $roleName]);
                $this->command->info('Tạo role ' . $roleName);
            }

            $existingUser = User::role($roleName)->first();

            if (! $existingUser) {
                $user = User::create([
                    'name'              => ucfirst($roleName) . ' User',
                    'email'             => $roleName . '@example.com',
                    'password'          => Hash::make('abc1234$'),
                    'email_verified_at' => now(),
                ]);
                $user->assignRole($roleName);
                $this->command->info('Tạo user mới cho role ' . $roleName . ': ' . $user->email);
            } else {
                $this->command->info('Role ' . $roleName . ' đã có user: ' . $existingUser->name . ' (' . $existingUser->email . ')');
            }
        }

        // 4. Gán role administrator cho user Admin
        if ($admin && ! $admin->hasRole('administrator')) {
            $admin->assignRole('administrator');
            $this->command->info('Đã gán role administrator cho Admin user.');
        }
    }
}
