<?php

namespace App\Services;

use App\Models\Members\User;
use App\Models\SiteAdmin;
use Illuminate\Support\Facades\DB;

class AdminPermissionService
{
    public static function getPermissionsByToken(string $userToken): array
    {
        $user = User::where('USER_TOKEN', $userToken)
            ->first();

        if (! $user) {
            return [];
        }

        $admin = SiteAdmin::where('UNO', $user->USER_NO)
            ->first();

        if (! $admin) {
            return [];
        }

        $permissionCodes = DB::table('SITE_ADMIN_USER_ROLE AS ur')
            ->join('SITE_ADMIN_ROLE_PERMISSION AS rp', 'ur.ROLE_ID', '=', 'rp.ROLE_ID')
            ->join('SITE_ADMIN_PERMISSIONS AS p', 'rp.PERMISSION_ID', '=', 'p.ID')
            ->where('ur.USER_ID', $admin->A_IDX)
            ->pluck('p.CODE')
            ->toArray();

        return $permissionCodes;
    }

    public static function hasPermission(string $userToken, string $code): bool
    {
        $permissions = self::getPermissionsByToken($userToken);

        return in_array($code, $permissions);
    }
}
