<?php

namespace App\Support;

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

/** 平台账号在各站点上的角色绑定（API 展示用）。 */
final class AdminUserSiteBindingPresenter
{
    /**
     * @return list<array{site_id: int, site_code: string, site_name: string, role_slugs: list<string>}>
     */
    public static function bindingsFor(AdminUser $user): array
    {
        if ($user->hasPrimaryAgentBinding()) {
            return [];
        }

        $rows = DB::table('admin_user_site_roles as usr')
            ->join('admin_sites as s', 's.id', '=', 'usr.site_id')
            ->join('admin_roles as r', 'r.id', '=', 'usr.role_id')
            ->where('usr.admin_user_id', $user->id)
            ->orderBy('s.code')
            ->orderBy('r.slug')
            ->get(['usr.site_id', 's.code as site_code', 's.name as site_name', 'r.slug as role_slug']);

        /** @var array<int, array{site_id: int, site_code: string, site_name: string, role_slugs: list<string>}> $bySite */
        $bySite = [];
        foreach ($rows as $row) {
            $siteId = (int) $row->site_id;
            if (! isset($bySite[$siteId])) {
                $bySite[$siteId] = [
                    'site_id' => $siteId,
                    'site_code' => (string) $row->site_code,
                    'site_name' => (string) $row->site_name,
                    'role_slugs' => [],
                ];
            }
            $slug = (string) $row->role_slug;
            if ($slug !== '' && ! in_array($slug, $bySite[$siteId]['role_slugs'], true)) {
                $bySite[$siteId]['role_slugs'][] = $slug;
            }
        }

        foreach ($bySite as &$binding) {
            sort($binding['role_slugs']);
        }
        unset($binding);

        return array_values($bySite);
    }

    /**
     * @return list<array{id: int, code: string, name: string}>
     */
    public static function accessibleSitesFor(AdminUser $admin): array
    {
        return AdminIntegrationSiteAccess::queryFor($admin)
            ->get(['id', 'code', 'name'])
            ->map(static fn ($site): array => [
                'id' => (int) $site->id,
                'code' => (string) $site->code,
                'name' => (string) $site->name,
            ])
            ->values()
            ->all();
    }
}
