<?php

namespace App\Support;

use App\Models\AdminSite;
use App\Models\AdminUser;
use Illuminate\Database\Eloquent\Builder;

final class AdminIntegrationSiteAccess
{
    /**
     * @return Builder<AdminSite>
     */
    public static function queryFor(AdminUser $admin): Builder
    {
        $query = AdminSite::query()->orderBy('code');

        $siteIds = $admin->accessibleAdminSiteIds();
        if ($siteIds === null) {
            return $query;
        }

        if ($siteIds === []) {
            return $query->whereRaw('0 = 1');
        }

        return $query->whereIn('id', $siteIds);
    }

    public static function canAccess(AdminUser $admin, AdminSite $site): bool
    {
        $siteIds = $admin->accessibleAdminSiteIds();
        if ($siteIds === null) {
            return true;
        }

        return in_array((int) $site->id, $siteIds, true);
    }
}
