<?php

namespace App\Domains\Admin\Controllers;

use App\Models\Tenant;
use App\Models\User;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserListApiController extends CommonController
{
    public function __invoke(Request $request): JsonResponse
    {
        $tenantNames = Tenant::pluck('name', 'slug');

        $query = User::query();

        if ($this->tenant->slug === 'lv') {
            $query->orderBy('lastname')->orderBy('firstname');
        } else {
            $query->where('local_group', $this->tenant->slug)
                  ->orderBy('lastname')->orderBy('firstname');
        }

        $users = $query->get()->map(function ($user) use ($tenantNames) {
            return [
                'id' => $user->id,
                'firstname' => $user->firstname,
                'lastname' => $user->lastname,
                'nickname' => $user->nickname,
                'local_group' => $user->local_group,
                'local_group_name' => $tenantNames[$user->local_group] ?? $user->local_group,
                'active' => $user->active,
            ];
        });

        return response()->json(['users' => $users]);
    }
}
