<?php

namespace App\Support;

use App\Models\AdminRole;

/** 平台内置系统角色（超管 / 站点运营 / 代理）。 */
final class PlatformSystemRoles
{
    public const SLUG_SUPER_ADMIN = AdminRole::ROLE_SUPER_ADMIN;

    public const SLUG_AGENT = 'agent';

    public const SLUG_SITE_ADMIN = SiteOperatorRoles::SLUG_SITE_ADMIN;

    public const SLUG_SITE_FINANCE = SiteOperatorRoles::SLUG_SITE_FINANCE;

    public const SLUG_SITE_CS = SiteOperatorRoles::SLUG_SITE_CS;

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

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

    /** 超级管理员：平台内置，同步当前目录中的全部 `prd.*`。 */
    public static function ensureSuperAdminRole(): AdminRole
    {
        $role = AdminRole::query()->updateOrCreate(
            [
                'slug' => self::SLUG_SUPER_ADMIN,
                'scope_type' => AdminRole::SCOPE_SYSTEM,
            ],
            [
                'code' => self::SLUG_SUPER_ADMIN,
                'name' => '超级管理员',
                'description' => '平台内置角色，拥有全部权限',
                'status' => 1,
                'is_system' => true,
                'sort_order' => 10,
                'owner_agent_id' => null,
                'delegated_from_role_id' => null,
            ],
        );
        $role->syncAllActiveMenuActions();

        return $role->fresh() ?? $role;
    }

    public static function ensureAll(): void
    {
        self::ensureSuperAdminRole();
        SiteAdminDefaultRolePermissions::ensurePlatformSiteAdminRole();
        SiteFinanceDefaultRolePermissions::ensurePlatformSiteFinanceRole();
        SiteCsDefaultRolePermissions::ensurePlatformSiteCsRole();
        AgentDefaultRolePermissions::ensurePlatformAgentRole();
    }
}
