<?php

namespace App\Domains\Identity\Actions;

use App\Domains\Tenancy\Models\Branch;
use App\Domains\Tenancy\Models\Tenant;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class SeedDemoUsersAction
{
    public function execute(Tenant $tenant, Branch $branch): void
    {
        DB::transaction(function () use ($tenant, $branch) {
            if (User::query()->where('tenant_id', $tenant->getKey())->count() > 1) {
                return;
            }

            $users = [
                ['full_name' => 'Nour Manager', 'email' => 'manager+'.strtolower($tenant->slug).'@example.com', 'role' => 'Sales Manager'],
                ['full_name' => 'Maya Agent', 'email' => 'agent+'.strtolower($tenant->slug).'@example.com', 'role' => 'Sales Agent'],
            ];

            app(PermissionRegistrar::class)->setPermissionsTeamId($tenant->getKey());

            foreach ($users as $attributes) {
                $user = User::query()->create([
                    'tenant_id' => $tenant->getKey(),
                    'branch_id' => $branch->getKey(),
                    'full_name' => $attributes['full_name'],
                    'email' => $attributes['email'],
                    'password' => 'Password123!',
                    'status' => 'active',
                ]);

                $role = Role::findByName($attributes['role'], 'web');
                $user->syncRoles([$role]);
            }

            app(PermissionRegistrar::class)->setPermissionsTeamId(null);
        });
    }
}
