<?php

namespace App\Http\Controllers;

use App\Enums\CampaignStatus;
use App\Http\Requests\CampaignStoreRequest;
use App\Http\Requests\CampaignUpdateRequest;
use App\Models\Campaign;
use App\Services\CampaignService;
use App\Services\UserService;
use App\Services\CreatorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CampaignsController extends Controller
{
    protected $service;
    protected $userService;
    protected $creatorService;

    public function __construct(
        CampaignService $service,
        UserService $userService,
        CreatorService $creatorService
    ) {
        $this->service = $service;
        $this->userService = $userService;
        $this->creatorService = $creatorService;
    }

    public function index(Request $request)
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Campaign::class, $organization]);

        $users = $this->userService->getListForTable($this->getOrgHex(), [], 1000);
        $usersList = $users->getCollection()->map(function ($user) {
            return [
                'id' => $user->hex_id,
                'display_name' => $user->display_name ?? $user->name,
            ];
        })->values();

        return view('pages.campaigns', [
            'page_title' => 'Quản Lý Chiến Dịch',
            'can_export' => auth()->user()->hasRole('owner') || auth()->user()->hasRole('admin'),
            'users' => $usersList->toArray(),
        ]);
    }

    public function data(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Campaign::class, $organization]);

        $filters = [
            'keyword' => $request->get('keyword'),
            'status' => $request->get('status'),
            'sort_field' => $request->get('sort_field'),
            'sort_direction' => $request->get('sort_direction'),
        ];
        $perPage = (int)$request->get('per_page', 10);

        $pageData = $this->service->getListForTable($this->getOrgHex(), $filters, $perPage);

        $rows = $pageData->getCollection()->map(function ($campaign) {
            $brief = $campaign->relationLoaded('brief') ? $campaign->brief : null;
            $assignedUser = $campaign->relationLoaded('assignedTo') ? $campaign->assignedTo : null;
            return [
                'id' => $this->formatCampaignId($campaign),
                'campaign_name' => $campaign->campaign_name,
                'product_name' => $campaign->product_name,
                'assigned_to_name' => $assignedUser?->display_name ?? $assignedUser?->name,
                'assigned_to_id' => $this->resolveUserHexId($assignedUser),
                'status' => $campaign->status,
                'start_date' => optional($campaign->start_date)->toDateString(),
                'end_date' => optional($campaign->end_date)->toDateString(),
                'description' => $campaign->description,
                'notes' => $campaign->notes,
                'created_at' => optional($campaign->created_at)->toIso8601String(),
                'koc_count' => (int)($campaign->bookings_count ?? 0),
                'cast_cost' => (int)($campaign->bookings_sum_cast_cost ?? 0),
                'sample_cost' => (int)($campaign->bookings_sum_sample_cost ?? 0),
                'shipping_cost' => (int)($campaign->bookings_sum_shipping_cost ?? 0),
                'total_cost' => (int)($campaign->total_cost ?? 0),
                'has_brief' => !is_null($brief),
            ];
        })->values();

        return response()->json([
            'data' => $rows,
            'pagination' => [
                'current_page' => $pageData->currentPage(),
                'per_page' => $pageData->perPage(),
                'total' => $pageData->total(),
                'last_page' => $pageData->lastPage(),
            ],
        ]);
    }

    public function metrics(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Campaign::class, $organization]);

        $allCampaigns = $this->service->getListForTable($this->getOrgHex(), [], 1000);
        $campaignsData = $allCampaigns->getCollection();

        $totalCampaigns = $campaignsData->count();
        $runningCampaigns = $campaignsData->filter(fn($c) => $c->status === CampaignStatus::ACTIVE->value)->count();

        $totalKocs = (int) $campaignsData->sum('bookings_count');
        $totalCastCost = (int) $campaignsData->sum('bookings_sum_cast_cost');
        $totalSampleCost = (int) $campaignsData->sum('bookings_sum_sample_cost');
        $totalShippingCost = (int) $campaignsData->sum('bookings_sum_shipping_cost');

        return response()->json([
            'total_campaigns' => $totalCampaigns,
            'running_campaigns' => $runningCampaigns,
            'total_kocs' => $totalKocs,
            'total_cast_cost' => $totalCastCost,
            'total_sample_cost' => $totalSampleCost,
            'total_shipping_cost' => $totalShippingCost,
            'total_all_costs' => $totalCastCost + $totalSampleCost + $totalShippingCost,
        ]);
    }

    public function getBrief(Request $request, $campaignId): JsonResponse
    {
        $campaign = $this->service->getCampaignById($campaignId, $this->getOrgHex());

        if (!$campaign) {
            return response()->json(['exists' => false, 'message' => 'Không tìm thấy chiến dịch'], 404);
        }

        $brief = $this->service->getCampaignWithBrief($campaignId, $this->getOrgHex())?->brief;

        if (!$brief) {
            return response()->json(['exists' => false, 'data' => null]);
        }

        return response()->json([
            'exists' => true,
            'data' => [
                'id' => $brief->id ? (strlen($brief->id) === 16 ? bin2hex($brief->id) : $brief->id) : null,
                'product_name' => $brief->product_name,
                'product_type' => $brief->product_type,
                'form_shape' => $brief->form_shape,
                'material' => $brief->material,
                'color' => $brief->color,
                'size' => $brief->size,
                'price' => $brief->price,
                'target_audience' => $brief->target_audience,
                'category' => $brief->category,
                'video_type' => $brief->video_type,
                'video_goal' => $brief->video_goal,
                'shop_handle' => $brief->shop_handle,
                'koc_voucher_code' => $brief->koc_voucher_code,
                'product_link' => $brief->product_link,
                'product_hashtags' => $brief->product_hashtags,
                'category_hashtags' => $brief->category_hashtags,
                'product_image_url' => $brief->product_image_url,
                'talks' => $brief->talks ?? [],
                'guidelines' => $brief->guidelines ?? [],
                'hooks' => $brief->hooks ?? [],
                'ctas' => $brief->ctas ?? [],
                'notes' => $brief->notes_json ?? [],
            ],
        ]);
    }

    public function updateBrief(Request $request, $campaignId): JsonResponse
    {
        $campaign = $this->service->getCampaignById($campaignId, $this->getOrgHex());

        if (!$campaign) {
            return response()->json(['message' => 'Không tìm thấy chiến dịch'], 404);
        }

        $data = $request->validate([
            'product_name' => 'nullable|string',
            'product_type' => 'nullable|string',
            'form_shape' => 'nullable|string',
            'material' => 'nullable|string',
            'color' => 'nullable|string',
            'size' => 'nullable|string',
            'price' => 'nullable|integer',
            'target_audience' => 'nullable|string',
            'category' => 'nullable|string',
            'video_type' => 'nullable|string',
            'video_goal' => 'nullable|string',
            'shop_handle' => 'nullable|string',
            'koc_voucher_code' => 'nullable|string',
            'product_link' => 'nullable|string',
            'product_hashtags' => 'nullable|string',
            'category_hashtags' => 'nullable|string',
            'product_image_url' => 'nullable|string',
            'talks' => 'nullable|array',
            'guidelines' => 'nullable|array',
            'hooks' => 'nullable|array',
            'ctas' => 'nullable|array',
            'notes' => 'nullable|array',
        ]);

        if (isset($data['notes'])) {
            $data['notes_json'] = $data['notes'];
            unset($data['notes']);
        }

        $updated = $this->service->updateCampaignBrief($campaignId, $data, $this->getOrgHex());

        if (!$updated) {
            return response()->json(['message' => 'Cập nhật brief thất bại'], 400);
        }

        return response()->json([
            'success' => true,
            'message' => 'Brief được cập nhật thành công',
            'id' => $updated->id ? (strlen($updated->id) === 16 ? bin2hex($updated->id) : $updated->id) : null,
        ]);
    }

    public function listJson(Request $request)
    {
        $limit = (int) $request->query('limit', 500);
        $campaigns = $this->service->getListWithPaginate($this->getOrgHex(), min($limit, 500));

        $data = $campaigns->map(function ($campaign) {
            return [
                'id' => $this->formatCampaignId($campaign),
                'campaign_name' => $campaign->campaign_name,
                'status' => $campaign->status,
            ];
        });

        return response()->json($data);
    }

    public function show(Request $request, $id)
    {
        $campaign = $this->service->getCampaignById($id, $this->getOrgHex());

        if (!$campaign) {
            return redirect()->route('campaigns')->with('error', 'Không tìm thấy chiến dịch');
        }

        $organization = $request->attributes->get('current_organization');
        $this->authorize('view', [$campaign, $organization]);

        $orgHex = $this->getOrgHex();

        // [TỐI ƯU] Load campaign with bookings — phiên bản nhẹ, lazy load bookingNotes
        $campaignWithRelations = $this->service->getCampaignWithBookingsLight($id, $orgHex);

        // [TỐI ƯU] Users — chỉ select columns cần thiết, limit 200
        $users = \App\Models\User::whereHas('organization', function ($q) use ($orgHex) {
                $q->where('id', hex2bin($orgHex));
            })
            ->select(['id', 'display_name', 'name'])
            ->limit(200)
            ->get()
            ->map(function ($user) {
                return [
                    'id' => $user->hex_id,
                    'display_name' => $user->display_name ?? $user->name,
                ];
            })
            ->values()
            ->toArray();

        $user = auth()->user();
        $isOwnerOrAdmin = $user->hasRole('owner') || $user->hasRole('admin');

        // [TỐI ƯU] Pre-compute stats ở PHP
        $bookings = $campaignWithRelations->bookings ?? collect();
        $stats = $this->computeBookingStats($bookings);

        // [TỐI ƯU] Map bookings → format giống detailJson() response
        $allKocs = $bookings->map(function ($booking) use ($orgHex) {
            return $this->formatBookingForDetail($booking, $orgHex);
        })->values()->toArray();

        return view('pages.campaigns.show', [
            'page_title' => 'Chi Tiết Chiến Dịch',
            'campaign' => $campaignWithRelations,
            'campaignId' => $this->formatCampaignId($campaignWithRelations),
            'users' => $users,
            'can_export' => $isOwnerOrAdmin,
            'can_export_pdf' => true,
            // Inject pre-computed data để Alpine không cần gọi detailJson()
            '_initialKocs' => $allKocs,
            '_initialStats' => $stats,
        ]);
    }

    /**
     * [TỐI ƯU] Pre-compute booking stats ở PHP thay vì client-side
     */
    private function computeBookingStats($bookings): array
    {
        $statusValues = \App\Enums\BookingStatus::values();
        $stats = [
            'not_contacted' => 0, 'pending' => 0, 'not_approved' => 0,
            'negotiating' => 0, 'confirmed' => 0, 'completed' => 0,
            'castCost' => 0, 'sampleCost' => 0, 'shippingCost' => 0, 'totalCost' => 0,
        ];

        foreach ($bookings as $b) {
            $s = $b->status ?? 'not_contacted';
            if (isset($stats[$s])) $stats[$s]++;
            $stats['castCost'] += (int)($b->cast_cost ?? 0);
            $stats['sampleCost'] += (int)($b->sample_cost ?? 0);
            $stats['shippingCost'] += (int)($b->shipping_cost ?? 0);
        }
        $stats['totalCost'] = $stats['castCost'] + $stats['sampleCost'] + $stats['shippingCost'];

        return $stats;
    }

    public function detailJson(Request $request, $id): JsonResponse
    {
        $campaign = $this->service->getCampaignWithBookings($id, $this->getOrgHex());

        if (!$campaign) {
            return response()->json(['message' => 'Không tìm thấy chiến dịch'], 404);
        }

        $organization = $request->attributes->get('current_organization');
        $this->authorize('view', [$campaign, $organization]);

        $orgHex = $this->getOrgHex();

        $bookings = $campaign->bookings->map(function ($booking) use ($orgHex) {
            return $this->formatBookingForDetail($booking, $orgHex);
        });

        $campaignAssigned = $campaign->relationLoaded('assignedTo') ? $campaign->assignedTo : null;

        return response()->json([
            'id' => $this->formatCampaignId($campaign),
            'campaign_name' => $campaign->campaign_name,
            'product_name' => $campaign->product_name,
            'assigned_to_name' => $campaignAssigned?->display_name ?? $campaignAssigned?->name,
            'assigned_to_id' => $this->resolveUserHexId($campaignAssigned),
            'owner_name' => $campaignAssigned?->display_name ?? $campaignAssigned?->name,
            'status' => $campaign->status,
            'start_date' => optional($campaign->start_date)->toDateString(),
            'end_date' => optional($campaign->end_date)->toDateString(),
            'notes' => $campaign->notes,
            'created_at' => optional($campaign->created_at)->toIso8601String(),
            'campaign_kocs' => $bookings,
        ]);
    }

    /**
     * Format booking data cho detail response
     */
    private function formatBookingForDetail($booking, ?string $orgHex): array
    {
        $creator = $booking->creator;
        if (!$creator && $booking->creator_id) {
            $rawCreatorId = $booking->getAttributes()['creator_id'] ?? $booking->creator_id;
            $creatorHexId = (is_string($rawCreatorId) && strlen($rawCreatorId) === 16)
                ? bin2hex($rawCreatorId)
                : (string) $rawCreatorId;
            $creator = $this->creatorService->getCreatorById($creatorHexId, $orgHex);
        }

        $assignedUser = $this->resolveBookingAssignedUser($booking, $orgHex);
        $rawAssignedId = $booking->getAttributes()['assigned_to_id'] ?? null;
        $assignedToIdHex = $rawAssignedId
            ? ((is_string($rawAssignedId) && strlen($rawAssignedId) === 16) ? bin2hex($rawAssignedId) : $rawAssignedId)
            : null;

        return [
            'id' => $this->formatCampaignId($booking),
            'creator_name' => $creator?->creator_name,
            'koc_id' => ($booking->getAttributes()['creator_id'] ?? null)
                ? ((is_string($booking->getAttributes()['creator_id']) && strlen($booking->getAttributes()['creator_id']) === 16)
                    ? bin2hex($booking->getAttributes()['creator_id'])
                    : $booking->getAttributes()['creator_id'])
                : null,
            'koc' => $creator ? [
                'id' => $this->formatCampaignId($creator),
                'creator_name' => $creator->creator_name,
                'tiktok_link' => $creator->tiktok_link,
                'facebook_link' => $creator->facebook_link,
                'instagram_link' => $creator->instagram_link,
                'contact_phone' => $creator->contact_phone,
                'contact_zalo' => $creator->contact_zalo,
                'contact_email' => $creator->contact_email,
                'address' => $creator->address,
            ] : null,
            'owner' => $assignedUser ? [
                'id' => $this->formatCampaignId($assignedUser),
                'display_name' => $assignedUser->display_name ?? $assignedUser->name,
            ] : null,
            'assigned_to_id' => $assignedToIdHex,
            'status' => $booking->status,
            'type' => $booking->type ?? 'video',
            'created_at' => optional($booking->created_at)->toIso8601String(),
            'engagement_natural' => $booking->engagement_natural,
            'engagement_ads' => $booking->engagement_ads,
            'cast_cost' => $booking->cast_cost,
            'sample_cost' => $booking->sample_cost,
            'shipping_cost' => $booking->shipping_cost,
            'price_quote' => $booking->price_quote,
            'quote' => $booking->price_quote,
            'order_code' => $booking->order_code,
            'send_date' => optional($booking->send_date)->toDateString(),
            'eta_date' => optional($booking->eta_date)->toDateString(),
            'air_date' => optional($booking->bookingVideo?->air_date)->toDateString(),
            'number_of_videos' => $booking->bookingVideo?->number_of_videos ?? 0,
            'sample_type' => $booking->bookingLivestream?->sample_type,
            'deal_live_registration' => $booking->bookingLivestream?->deal_live_registration,
            'video_links' => $booking->videos->map(function ($video) {
                return [
                    'id' => $this->formatCampaignId($video),
                    'url' => $video->url,
                    'status' => $video->status,
                    'spark_ads' => $video->spark_ads ?? '',
                    'platform' => $video->platform ?? null,
                    'views' => $video->views ?? null,
                    'likes' => $video->likes ?? null,
                ];
            })->values(),
            // [TỐI ƯU] Không load bookingNotes trong eager load — lazy load khi cần
            'booking_notes' => [],
            'booking_notes_count' => (int)($booking->booking_notes_count ?? 0),
        ];
    }

    /**
     * [TỐI ƯU Phase 2] API bookings server-side pagination + filter theo type
     * Trả về phân trang, tôn trọng pageSize từ dropdown của user.
     * Stats vẫn được tính từ PHP pre-computed (không bị ảnh hưởng).
     */
    public function bookingsJson(Request $request, $id): JsonResponse
    {
        $campaign = $this->service->getCampaignById($id, $this->getOrgHex());
        if (!$campaign) {
            return response()->json(['message' => 'Not found'], 404);
        }

        $organization = $request->attributes->get('current_organization');
        $this->authorize('view', [$campaign, $organization]);

        $orgHex = $this->getOrgHex();
        $type = $request->query('type', 'all');
        $page = max(1, (int) $request->query('page', 1));
        $perPage = min(100, max(5, (int) $request->query('per_page', 15)));

        $bookings = $campaign->bookings()
            ->with(['creator', 'assignedTo', 'videos', 'bookingVideo', 'bookingLivestream'])
            ->withCount('bookingNotes')
            ->when($type !== 'all', fn($q) => $q->where('type', $type))
            ->orderBy('created_at', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        $items = $bookings->map(fn($b) => $this->formatBookingForDetail($b, $orgHex));

        return response()->json([
            'data' => $items,
            'pagination' => [
                'current_page' => $bookings->currentPage(),
                'per_page' => $bookings->perPage(),
                'total' => $bookings->total(),
                'last_page' => $bookings->lastPage(),
            ],
        ]);
    }

    public function store(CampaignStoreRequest $request)
    {
        $validated = $request->validated();
        $validated['start_date'] = !empty($validated['start_date']) ? $validated['start_date'] : null;
        $validated['end_date'] = !empty($validated['end_date']) ? $validated['end_date'] : null;
        $validated['assigned_to_id'] = !empty($validated['assigned_to_id']) ? $validated['assigned_to_id'] : null;
        $validated['created_by_id'] = auth()->id();

        $campaign = $this->service->createCampaign($validated, $this->getOrgHex());

        if ($this->expectsJsonResponse($request)) {
            return response()->json([
                'success' => true,
                'message' => 'Chiến dịch được tạo thành công',
                'data' => [
                    'id' => $this->formatCampaignId($campaign),
                    'campaign_name' => $campaign->campaign_name,
                ],
            ]);
        }

        return redirect()->route('campaigns')->with('success', 'Chiến dịch được tạo thành công');
    }

    public function storeBrief(Request $request, $campaignId)
    {
        $validated = $request->validate([
            'product_name' => 'nullable|string',
            'product_type' => 'nullable|string',
            'form_shape' => 'nullable|string',
            'material' => 'nullable|string',
            'color' => 'nullable|string',
            'size' => 'nullable|string',
            'price' => 'nullable|integer',
            'target_audience' => 'nullable|string',
            'category' => 'nullable|string',
            'video_type' => 'nullable|string',
            'video_goal' => 'nullable|string',
            'shop_handle' => 'nullable|string',
            'koc_voucher_code' => 'nullable|string',
            'product_link' => 'nullable|string',
            'product_hashtags' => 'nullable|string',
            'category_hashtags' => 'nullable|string',
            'product_image_url' => 'nullable|string',
        ]);

        $updated = $this->service->updateCampaignBrief($campaignId, $validated, $this->getOrgHex());

        if (!$updated) {
            return redirect()->back()->with('error', 'Không tìm thấy chiến dịch trong organization hiện tại');
        }

        return redirect()->back()->with('success', 'Brief được cập nhật thành công');
    }

    public function destroyBrief(Request $request, $campaignId): JsonResponse
    {
        $deleted = $this->service->deleteCampaignBrief($campaignId, $this->getOrgHex());

        if (!$deleted) {
            return response()->json(['message' => 'Không tìm thấy chiến dịch'], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'Brief đã được xóa',
        ]);
    }

    public function uploadBriefImage(Request $request, $campaignId): JsonResponse
    {
        $campaign = $this->service->getCampaignById($campaignId, $this->getOrgHex());
        if (!$campaign) {
            return response()->json(['message' => 'Không tìm thấy chiến dịch'], 404);
        }

        $request->validate([
            'file' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:10240',
        ]);

        $url = $this->service->uploadBriefImage($request->file('file'), $campaignId);

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

    public function deleteBriefImage(Request $request, $campaignId): JsonResponse
    {
        $campaign = $this->service->getCampaignById($campaignId, $this->getOrgHex());
        if (!$campaign) {
            return response()->json(['message' => 'Không tìm thấy chiến dịch'], 404);
        }

        $request->validate(['url' => 'required|string']);

        $this->service->deleteBriefImage($request->input('url'));

        return response()->json(['success' => true]);
    }

    public function update(CampaignUpdateRequest $request, $id)
    {
        $validated = $request->validated();
        $validated['start_date'] = !empty($validated['start_date']) ? $validated['start_date'] : null;
        $validated['end_date'] = !empty($validated['end_date']) ? $validated['end_date'] : null;
        $validated['assigned_to_id'] = !empty($validated['assigned_to_id']) ? $validated['assigned_to_id'] : null;
        $updated = $this->service->updateCampaign($id, $validated, $this->getOrgHex());

        if (!$updated) {
            if ($this->expectsJsonResponse($request)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Không tìm thấy chiến dịch trong organization hiện tại',
                ], 404);
            }

            return redirect()->route('campaigns')->with('error', 'Không tìm thấy chiến dịch trong organization hiện tại');
        }

        if ($this->expectsJsonResponse($request)) {
            return response()->json([
                'success' => true,
                'message' => 'Chiến dịch được cập nhật thành công',
            ]);
        }

        return redirect()->route('campaigns')->with('success', 'Chiến dịch được cập nhật thành công');
    }

    public function destroy(Request $request, $id)
    {
        $campaign = $this->service->getCampaignById($id, $this->getOrgHex());

        if (!$campaign) {
            if ($this->expectsJsonResponse($request)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Không tìm thấy chiến dịch trong organization hiện tại',
                ], 404);
            }

            return redirect()->route('campaigns')->with('error', 'Không tìm thấy chiến dịch trong organization hiện tại');
        }

        $organization = $request->attributes->get('current_organization');
        $this->authorize('delete', [$campaign, $organization]);

        $deleted = $this->service->deleteCampaign($id, $this->getOrgHex());

        if (!$deleted) {
            if ($this->expectsJsonResponse($request)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Không thể xóa chiến dịch',
                ], 400);
            }

            return redirect()->route('campaigns')->with('error', 'Không thể xóa chiến dịch');
        }

        if ($this->expectsJsonResponse($request)) {
            return response()->json([
                'success' => true,
                'message' => 'Chiến dịch được xóa thành công',
            ]);
        }

        return redirect()->route('campaigns')->with('success', 'Chiến dịch được xóa thành công');
    }

    private function resolveUserHexId($user): ?string
    {
        if (!$user) return null;
        if (method_exists($user, 'getHexIdAttribute')) {
            return $user->hex_id;
        }
        $raw = $user->getAttributes()['id'] ?? null;
        if (is_string($raw) && strlen($raw) === 16) return bin2hex($raw);
        return $raw;
    }

    private function formatCampaignId($campaign): string
    {
        $raw = $campaign->getAttributes()['id'] ?? $campaign->id;
        if (is_string($raw) && preg_match('/^[a-f0-9]{32}$/i', $raw) === 1) {
            return $raw;
        }
        if (is_string($raw) && strlen($raw) === 16) {
            return bin2hex($raw);
        }
        return (string)$campaign->id;
    }

    private function resolveBookingAssignedUser($booking, ?string $orgHex)
    {
        if ($booking->assignedTo) {
            return $booking->assignedTo;
        }

        $rawAssignedId = $booking->getAttributes()['assigned_to_id'] ?? null;
        if (!$rawAssignedId) {
            return null;
        }

        $hexId = (is_string($rawAssignedId) && strlen($rawAssignedId) === 16)
            ? bin2hex($rawAssignedId)
            : (string) $rawAssignedId;

        return $this->userService->getStaffById($hexId, $orgHex);
    }
}