<?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 AdminUsersSeeder extends Seeder
{
    public function run(): void
    {
        if (app()->environment('production')) {
            $this->command->warn('AdminUsersSeeder skipped in production.');

            return;
        }

        $context = app(CurrentContext::class);

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

    private function seedUsers(): void
    {
        $tenantId = app(CurrentContext::class)->tenantId();
        if ($tenantId === null) {
            throw new RuntimeException('AdminUsersSeeder requires a bound tenant context.');
        }

        // Dev-only convenience account: only the superadmin. The exported
        // operations staff (reps, cashiers, managers) is deliberately not
        // recreated in fresh installs or test instances.
        $admin = User::updateOrCreate(
            ['tenant_id' => $tenantId, 'email' => 'admin@vellix.com'],
            [
                'name' => 'Admin User',
                'password' => Hash::make('password'),
                'status' => User::STATUS_ACTIVE,
                'email_verified_at' => now(),
            ],
        );
        $this->assignRole($admin, 'Full Administrator');
    }

    private function assignRole(User $user, string $roleName): void
    {
        $role = Role::query()->where('name', $roleName)->firstOrFail();

        // Multi-role: keep role_id as the primary for display, assign via the pivot.
        $user->update(['role_id' => $role->id]);
        $user->roles()->syncWithoutDetaching([$role->id]);
        $user->flushPermissionCache();
    }
}
