<?php

namespace Modules\ClinicLab\Entities\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Small helper for the test catalogue: resolve an ERP lab-test product by name
 * so pricing/billing can be linked. Reads the core `products` table read-only.
 */
class CatalogService
{
    /**
     * Find a business's lab-test product id by (case-insensitive) name match.
     * Returns null when the ERP product doesn't exist — the catalog row is still
     * valid, just non-billable.
     */
    public function findProductIdByName(int $businessId, string $name): ?int
    {
        try {
            if (! Schema::hasTable('products')) {
                return null;
            }
            $id = DB::table('products')
                ->where('business_id', $businessId)
                ->whereRaw('LOWER(name) = ?', [mb_strtolower(trim($name))])
                ->value('id');
            return $id ? (int) $id : null;
        } catch (\Throwable $e) {
            return null;
        }
    }

    /** Active lab-test products for a business, for the catalog product picker. */
    public function labProducts(int $businessId)
    {
        try {
            if (! Schema::hasTable('products')) {
                return collect();
            }
            return DB::table('products')
                ->where('business_id', $businessId)
                ->orderBy('name')
                ->limit(500)
                ->get(['id', 'name']);
        } catch (\Throwable $e) {
            return collect();
        }
    }
}
