<?php

namespace Database\Seeders;

use App\Models\Central\Tenant;
use App\Models\Role;
use App\Models\User;
use App\Services\CurrentContext;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DemoRepresentativeUserSeeder extends Seeder
{
    /**
     * Seed a demo Sales Representative user.
     *
     * Credentials:
     *   Email:    rep@vellix.lk
     *   Password: Rep@Demo2024
     */
    public function run(): void
    {
        $context = app(CurrentContext::class);

        if ($context->hasTenant()) {
            $this->seedRepUser();
        } else {
            Tenant::all()->each(function (Tenant $tenant) use ($context): void {
                $context->runForTenant($tenant, fn () => $this->seedRepUser());
            });
        }
    }

    private function seedRepUser(): void
    {
        // The "Sales Person" role + its permissions are defined in
        // SystemRoleDefinition and seeded by PermissionsAndRolesSeeder.
        $role = Role::firstOrCreate(
            ['name' => 'Sales Person'],
            [
                'description' => 'Field sales representative — Sales Orders workflow only (mobile).',
                'is_system' => true,
                'is_full_admin' => false,
                'is_active' => true,
            ]
        );

        $user = User::updateOrCreate(
            ['email' => 'rep@vellix.lk'],
            [
                'name' => 'Demo Representative',
                'password' => Hash::make('Rep@Demo2024'),
                'role_id' => $role->id,
                'status' => User::STATUS_ACTIVE,
                'email_verified_at' => now(),
            ]
        );

        $user->roles()->syncWithoutDetaching([$role->id]);
        $user->flushPermissionCache();

        $this->command->info('Demo representative user created:');
        $this->command->line('  Email:    rep@vellix.lk');
        $this->command->line('  Password: Rep@Demo2024');
        $this->command->line('  Role:     Sales Person');
    }
}
