<?php

use App\Domain\Identity\Services\TerminologyService;
use App\Domain\Identity\Support\Terminology;
use App\Domain\Shared\Context\BranchContext;

if (! function_exists('terms')) {
    /**
     * The vocabulary of the branch currently being worked in.
     *
     * This is the adapter TerminologyService deliberately does not contain:
     * the service takes an explicit branch id so it stays callable from a
     * queue, and this reads the session so a Blade file does not have to.
     *
     * Pass $branchId to label a record that belongs to a branch other than the
     * one on screen — a cross-branch report row, a receipt reprinted from
     * elsewhere. Leave it null everywhere else.
     *
     * $locale is for the few writes that store both languages side by side —
     * a base price carries name_ar and name — and must not both come back in
     * whichever language the session happens to be in.
     */
    function terms(?int $branchId = null, ?string $locale = null): Terminology
    {
        $branchId ??= app(BranchContext::class)->branchId();

        return app(TerminologyService::class)->for($branchId, $locale);
    }
}

if (! function_exists('term')) {
    /**
     * One label from the current branch's vocabulary.
     *
     *   term('member')          عضو      / مقيم        / مشترك
     *   term('members')         الأعضاء  / المقيمون    / المشتركون
     *   term('non_member')      غير عضو  / غير مقيم    / زائر يومي
     *   term('membership')      العضوية  / الإقامة     / الاشتراك
     *   term('membership_id')   رقم العضوية / رقم الإقامة
     *   term('member_price')    سعر العضو   / سعر المقيم
     *
     * Unknown keys throw rather than returning the key back — a typo that
     * printed "membershipp_type" onto a receipt would survive review, and an
     * exception in development will not.
     */
    function term(string $key, ?int $branchId = null): string
    {
        return terms($branchId)->get($key);
    }
}

if (! function_exists('membership_label')) {
    /**
     * The label for a membership_type value.
     *
     * Takes the enum, the raw column ('member' / 'non_member') or a CSV cell,
     * because callers have all three: a hydrated model, a ->pluck() of the
     * column, and an uploaded file being previewed before it is imported.
     */
    function membership_label(
        \App\Domain\Participant\Enums\MembershipType|string|null $membershipType,
        ?int $branchId = null,
    ): string {
        $value = $membershipType instanceof \App\Domain\Participant\Enums\MembershipType
            ? $membershipType->value
            : $membershipType;

        return $value === 'member'
            ? term('member', $branchId)
            : term('non_member', $branchId);
    }
}
