<?php

namespace Modules\Webhooks\Support;

use App\Models\Order;
use App\Models\Table;

class BranchResolver
{
    public static function resolve(object $event, ?int $branchId, array $data = []): ?int
    {
        if ($branchId) {
            return $branchId;
        }

        foreach (['order', 'reservation', 'kot', 'printJob'] as $property) {
            if (property_exists($event, $property) && isset($event->{$property}) && $event->{$property}) {
                $modelBranchId = $event->{$property}->branch_id ?? null;
                if ($modelBranchId) {
                    return $modelBranchId;
                }
            }
        }

        if (! empty($data['branch_id'])) {
            return (int) $data['branch_id'];
        }

        if (! empty($data['table_id'])) {
            $tableBranchId = Table::where('id', $data['table_id'])->value('branch_id');
            if ($tableBranchId) {
                return (int) $tableBranchId;
            }
        }

        if (! empty($data['order_id'])) {
            $orderBranchId = Order::where('id', $data['order_id'])->value('branch_id');
            if ($orderBranchId) {
                return (int) $orderBranchId;
            }
        }

        return null;
    }
}
