<?php

namespace Database\Seeders;

use App\Models\PlatformRole;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        // Resolve the super_admin platform role (seeded by PlatformRoleSeeder)
        $superAdminRole = PlatformRole::where('name', 'super_admin')->first();

        // Platform Super Admin (no organization — manages the platform itself)
        $platformAdmin = User::firstOrCreate(
            ['email' => 'admin@inventino.shop'],
            [
                'name'               => 'Inventino Admin',
                'password'           => Hash::make('password'),
                'phone'              => '1234567890',
                'is_active'          => true,
                'email_verified_at'  => now(),
            ]
        );

        // forceFill to assign privileged fields excluded from $fillable
        $needsSave = false;
        if (! $platformAdmin->is_platform_admin) {
            $platformAdmin->forceFill(['is_platform_admin' => true]);
            $needsSave = true;
        }
        if ($superAdminRole && $platformAdmin->platform_role_id !== $superAdminRole->id) {
            $platformAdmin->forceFill(['platform_role_id' => $superAdminRole->id]);
            $needsSave = true;
        }
        if ($needsSave) {
            $platformAdmin->save();
        }

        // Org Admin (owner of their organization — highest org role)
        $admin = User::firstOrCreate(
            ['email' => 'manager@inventino.shop'],
            [
                'name'              => 'Store Manager',
                'password'          => Hash::make('password'),
                'phone'             => '0987654321',
                'is_active'         => true,
                'email_verified_at' => now(),
            ]
        );
        $admin->assignRole('admin');

        // Salesperson
        $salesperson = User::firstOrCreate(
            ['email' => 'cashier@inventino.shop'],
            [
                'name'              => 'John Cashier',
                'password'          => Hash::make('password'),
                'phone'             => '5555555555',
                'is_active'         => true,
                'email_verified_at' => now(),
            ]
        );
        $salesperson->assignRole('salesperson');
    }
}
