<?php

namespace Modules\Bms\Http\Controllers\Api;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsWizardSession;
use Modules\Bms\Services\Matching\MatchingEngine;

/**
 * Public matching endpoint for the client funnel. Runs the shared
 * MatchingEngine against a wizard session's answers (or ad-hoc body criteria)
 * and logs the run against the session/lead for sales context.
 */
class MatchController extends ApiController
{
    public function run(Request $request, MatchingEngine $engine, ?string $token = null)
    {
        // Build the (localized) reasons in the client's language.
        $lang = $request->input('lang', $request->getPreferredLanguage(['en', 'ar']));
        if (in_array($lang, ['ar', 'en'], true)) {
            app()->setLocale($lang);
        }

        $businessId = $this->publicBusinessId($request);
        $context = ['source' => 'client'];

        if ($token) {
            $session = BmsWizardSession::where('token', $token)->first();
            if (! $session) {
                return $this->fail('Not found', 404);
            }
            $businessId = $session->business_id;
            $context['wizard_session_id'] = $session->id;
            $context['lead_id'] = $session->lead_id;
            $criteria = [
                'attendees'        => $session->attendees,
                'fnb_level'        => $session->fnb_level,
                'venue_preference' => $session->venue_preference,
                'area_id'          => $session->area_id,
                'budget'           => $session->budget_max,
                'dates'            => $session->candidate_dates ?? [],
            ];
        } else {
            $criteria = $request->validate([
                'attendees'        => 'nullable|integer|min:0',
                'fnb_level'        => 'nullable|in:high_tea,drinks_only,set_menu,open_buffet,custom',
                'venue_preference' => 'nullable|in:open,closed,both',
                'area_id'          => 'nullable|integer',
                'budget'           => 'nullable|numeric|min:0',
                'dates'            => 'nullable|array',
            ]);
        }

        $outcome = $engine->run($businessId, $criteria);
        $engine->logRun($businessId, $outcome, $context);

        return $this->ok([
            'threshold'     => $outcome['threshold'],
            'matched_count' => $outcome['matched_count'],
            'results'       => $outcome['results'],
        ]);
    }
}
