# -*- coding: utf-8 -*-
"""业务层 · 组织机构服务（成员管理，消除 N+1）。"""
from __future__ import annotations

from fastapi import HTTPException

from ..infrastructure.repositories import Database


class OrgService:
    """机构/组织成员管理。"""

    def __init__(self, db: Database):
        self.db = db

    async def my_orgs(self, user_id: str) -> dict:
        """返回当前账号挂靠的所有机构及成员角色（支持一账号多机构，批量查避免 N+1）。"""
        members = await self.db.org_members.list_for_user(user_id)
        org_ids = [m["org_id"] for m in members]
        orgs = {o["id"]: o for o in await self.db.orgs.list_by_ids(org_ids)} if org_ids else {}
        return {"items": [
            {"org": orgs[m["org_id"]], "member_role": m["role"], "is_admin": m["is_admin"]}
            for m in members if m["org_id"] in orgs
        ]}

    async def add_member(self, org_id: str, username: str, role: str, actor: dict) -> dict:
        """添加机构成员（须机构 admin，用户名解析为 user_id）。"""
        org = await self.db.orgs.get(org_id)
        if org is None:
            raise HTTPException(status_code=404, detail="机构不存在")
        actor_members = await self.db.org_members.list_for_org(org_id)
        if not any(m["user_id"] == actor["id"] and m["is_admin"] for m in actor_members):
            raise HTTPException(status_code=403, detail="仅机构管理员可添加成员")
        user = await self.db.users.get_by_username(username)
        if user is None:
            raise HTTPException(status_code=404, detail="用户不存在")
        existing = await self.db.org_members.get(org_id, user["id"])
        if existing:
            return existing
        return await self.db.org_members.add_member(org_id, user["id"], role)
