<?php

namespace Modules\Webhooks\Support;

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

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

        if (property_exists($event, 'restaurant_id') && $event->restaurant_id) {
            return (int) $event->restaurant_id;
        }

        foreach (['order', 'reservation', 'kot', 'printJob', 'restaurant'] as $property) {
            if (property_exists($event, $property) && isset($event->{$property}) && $event->{$property}) {
                $model = $event->{$property};
                if (! empty($model->restaurant_id)) {
                    return (int) $model->restaurant_id;
                }
                if (! empty($model->branch_id)) {
                    $fromBranch = Branch::where('id', $model->branch_id)->value('restaurant_id');
                    if ($fromBranch) {
                        return (int) $fromBranch;
                    }
                }
            }
        }

        if ($branchId) {
            $fromBranch = Branch::where('id', $branchId)->value('restaurant_id');
            if ($fromBranch) {
                return (int) $fromBranch;
            }
        }

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

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

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

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

        return null;
    }
}
