<?php

namespace App\Http\Controllers\Api\Users;

use App\Domains\Tenancy\Models\Branch;
use App\Http\Controllers\Controller;
use App\Http\Requests\Users\StoreUserRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class UserStoreController extends Controller
{
    public function __invoke(StoreUserRequest $request): JsonResponse
    {
        $tenantId = $request->user()->tenant_id;
        $branchId = Branch::query()->where('tenant_id', $tenantId)->value('id');

        $user = User::query()->create([
            'tenant_id' => $tenantId,
            'branch_id' => $branchId,
            'full_name' => $request->validated('full_name'),
            'email' => $request->validated('email'),
            'phone' => $request->validated('phone'),
            'password' => $request->validated('password'),
            'status' => $request->validated('status') ?? 'active',
        ]);

        app(PermissionRegistrar::class)->setPermissionsTeamId($tenantId);
        $role = Role::findByName($request->validated('role'), 'web');
        $user->syncRoles([$role]);
        app(PermissionRegistrar::class)->setPermissionsTeamId(null);

        return response()->json([
            'data' => [
                'id' => $user->id,
                'fullName' => $user->full_name,
                'email' => $user->email,
                'status' => $user->status,
                'roles' => [$role->name],
            ],
        ], 201);
    }
}
