<?php

namespace Database\Seeders\Demo;

use App\Models\Branch;
use App\Models\People\SalesRep;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\Demo\Concerns\GeneratesDemoData;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

/**
 * Extra staff users (branch managers, an auditor, field sales reps) beyond
 * the admin/manager/rep accounts AdminUsersSeeder/DemoRepresentativeUserSeeder
 * already create. Reuses the existing system roles — no new roles invented.
 */
class StaffSeeder extends Seeder
{
    use GeneratesDemoData;

    public function run(): void
    {
        $branches = Branch::orderBy('id')->get();
        $managerRole = Role::where('name', 'Manager')->firstOrFail();
        $auditorRole = Role::where('name', 'Auditor')->firstOrFail();
        $repRole = Role::where('name', 'Sales Person')->firstOrFail();

        foreach ($branches as $branch) {
            $manager = $this->makeUser("{$branch->name} Manager");
            $this->assignRole($manager, $managerRole);
            $branch->update(['manager_user_id' => $manager->id]);
        }

        $auditor = $this->makeUser('Head Office Auditor');
        $this->assignRole($auditor, $auditorRole);

        $repNames = ['Nimal Perera', 'Kasuni Fernando', 'Ruwan Jayasuriya', 'Dilani Wickramasinghe', 'Chamara Silva'];
        foreach ($repNames as $i => $name) {
            $branch = $branches[$i % $branches->count()];
            $user = $this->makeUser($name);
            $this->assignRole($user, $repRole);

            SalesRep::create([
                'employee_id' => sprintf('REP-%03d', $i + 1),
                'user_id' => $user->id,
                'branch_id' => $branch->id,
                'full_name' => $name,
                'phone' => $this->srPhone(),
                'email' => $user->email,
                'territory' => $branch->city,
                'joined_date' => now()->subMonths(random_int(6, 36))->toDateString(),
                'is_active' => true,
            ]);
        }
    }

    private function makeUser(string $name): User
    {
        $email = strtolower(str_replace(' ', '.', $name)).'@vellix.lk';

        return User::updateOrCreate(
            ['email' => $email],
            [
                'name' => $name,
                'password' => Hash::make('password'),
                'status' => User::STATUS_ACTIVE,
                'email_verified_at' => now(),
            ],
        );
    }

    private function assignRole(User $user, Role $role): void
    {
        $user->update(['role_id' => $role->id]);
        $user->roles()->syncWithoutDetaching([$role->id]);
        $user->flushPermissionCache();
    }
}
