<?php

namespace Modules\MedNotify\Services;

use Modules\MedNotify\Entities\MednotifyPreference;

/**
 * Resolves the ONE effective preference row for a (user, event, channel),
 * choosing the most specific match. Precedence, high → low:
 *
 *   1. event_key = X , channel = Y   (exact)
 *   2. event_key = X , channel NULL  (this event, any channel)
 *   3. event_key NULL, channel = Y   (any event, this channel)
 *   4. event_key NULL, channel NULL  (global)
 *
 * Returns null when the user has set no matching preference (→ default:
 * enabled, immediate).
 */
class PreferenceResolver
{
    public static function resolve(int $businessId, int $userId, string $eventKey, string $channel): ?MednotifyPreference
    {
        $prefs = MednotifyPreference::where('business_id', $businessId)
            ->where('user_id', $userId)
            ->where(function ($q) use ($eventKey) {
                $q->whereNull('event_key')->orWhere('event_key', $eventKey);
            })
            ->where(function ($q) use ($channel) {
                $q->whereNull('channel')->orWhere('channel', $channel);
            })
            ->get();

        if ($prefs->isEmpty()) {
            return null;
        }

        // Score specificity: event match = 2, channel match = 1.
        return $prefs->sortByDesc(function (MednotifyPreference $p) use ($eventKey, $channel) {
            $score = 0;
            if ($p->event_key === $eventKey) {
                $score += 2;
            }
            if ($p->channel === $channel) {
                $score += 1;
            }

            return $score;
        })->first();
    }
}
