<?php

namespace Modules\Webhooks\Support;

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

class WebhookRouting
{
    /**
     * Decide if an event is allowed to dispatch for the given tenant/package.
     * Defaults to allow when no policy/default rows exist (backward compatible).
     */
    public static function allows(?int $restaurantId, ?int $branchId, ?int $packageId, string $module, string $eventKey): bool
    {
        if (Schema::hasTable('webhook_global_policies')) {
            $policy = DB::table('webhook_global_policies')
                ->where('event_key', $eventKey)
                ->where('module', $module)
                ->first();

            if ($policy) {
                if (! (bool) $policy->allowed) {
                    return false;
                }

                if ($packageId && $policy->allowed_packages !== null) {
                    $allowedPackages = json_decode($policy->allowed_packages, true) ?: [];
                    if (! empty($allowedPackages) && ! in_array($packageId, $allowedPackages, true)) {
                        return false;
                    }
                }
            }
        }

        if ($packageId && Schema::hasTable('webhook_package_defaults')) {
            $defaults = DB::table('webhook_package_defaults')
                ->where('package_id', $packageId)
                ->first();

            if ($defaults && $defaults->allowed_events !== null) {
                $allowedEvents = json_decode($defaults->allowed_events, true) ?: [];
                if (! empty($allowedEvents) && ! in_array($eventKey, $allowedEvents, true)) {
                    return false;
                }
            }
        }

        return true;
    }
}
