<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TenantUserApiController extends Controller
{
    /**
     * 테넌트 사용자 검색 (결재라인 담당자 선택용)
     */
    public function search(Request $request): JsonResponse
    {
        $tenantId = session('selected_tenant_id');
        $query = $request->input('q', '');

        $users = DB::table('users')
            ->join('user_tenants', function ($join) use ($tenantId) {
                $join->on('users.id', '=', 'user_tenants.user_id')
                    ->where('user_tenants.tenant_id', $tenantId)
                    ->where('user_tenants.is_active', true);
            })
            ->leftJoin('departments', function ($join) {
                $join->on('departments.id', '=', DB::raw('(
                    SELECT du.department_id FROM department_user du
                    WHERE du.user_id = users.id AND du.is_primary = 1
                    LIMIT 1
                )'));
            })
            ->whereNull('users.deleted_at')
            ->when($query, function ($q) use ($query) {
                $q->where(function ($sub) use ($query) {
                    $sub->where('users.name', 'like', "%{$query}%")
                        ->orWhere('users.email', 'like', "%{$query}%");
                });
            })
            ->orderBy('users.name')
            ->limit(30)
            ->select([
                'users.id',
                'users.name',
                'departments.name as department_name',
            ])
            ->get();

        return response()->json([
            'success' => true,
            'data' => $users,
        ]);
    }
}
