<?php

namespace App\Support;

use App\Models\AdminUser;
use Illuminate\Support\Facades\DB;

/** 接入站点平台账号内置角色（绑定 admin_user_site_roles，无代理节点）。 */
final class SiteOperatorRoles
{
    public const SLUG_SITE_ADMIN = 'site_admin';

    public const SLUG_SITE_FINANCE = 'site_finance';

    public const SLUG_SITE_CS = 'site_cs';

    /** @return list<string> */
    public static function slugs(): array
    {
        return [
            self::SLUG_SITE_ADMIN,
            self::SLUG_SITE_FINANCE,
            self::SLUG_SITE_CS,
        ];
    }

    public static function isSiteOperatorSlug(string $slug): bool
    {
        return in_array($slug, self::slugs(), true);
    }

    public static function userHasSiteOperatorRole(AdminUser $user): bool
    {
        if ($user->isSuperAdmin() || $user->hasPrimaryAgentBinding()) {
            return false;
        }

        return self::primarySiteOperatorSlug($user) !== null;
    }

    public static function userHasSiteAdminRole(AdminUser $user): bool
    {
        return self::primarySiteOperatorSlug($user) === self::SLUG_SITE_ADMIN;
    }

    public static function primarySiteOperatorSlug(AdminUser $user): ?string
    {
        if ($user->isSuperAdmin() || $user->hasPrimaryAgentBinding()) {
            return null;
        }

        $slug = DB::table('admin_user_site_roles as usr')
            ->join('admin_roles as r', 'r.id', '=', 'usr.role_id')
            ->where('usr.admin_user_id', $user->id)
            ->whereIn('r.slug', self::slugs())
            ->orderBy('usr.site_id')
            ->orderBy('r.sort_order')
            ->value('r.slug');

        return is_string($slug) && $slug !== '' ? $slug : null;
    }
}
