"""Organization service: CRUD + membership helpers."""

from __future__ import annotations

import uuid
from typing import Sequence

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.organization import OrgMember, Organization


async def list_organizations(db: AsyncSession) -> Sequence[Organization]:
    result = await db.execute(select(Organization).order_by(Organization.name))
    return result.scalars().all()


async def get_organization(db: AsyncSession, org_id: uuid.UUID) -> Organization | None:
    return await db.get(Organization, org_id)


async def get_organization_by_slug(db: AsyncSession, slug: str) -> Organization | None:
    result = await db.execute(select(Organization).where(Organization.slug == slug))
    return result.scalar_one_or_none()


async def create_organization(db: AsyncSession, **kwargs) -> Organization:
    org = Organization(**kwargs)
    db.add(org)
    await db.commit()
    await db.refresh(org)
    return org


async def is_member(db: AsyncSession, org_id: uuid.UUID, identity_id: uuid.UUID) -> bool:
    result = await db.execute(
        select(OrgMember).where(
            OrgMember.org_id == org_id,
            OrgMember.identity_id == identity_id,
        )
    )
    return result.scalar_one_or_none() is not None


async def add_member(
    db: AsyncSession, org_id: uuid.UUID, identity_id: uuid.UUID, role: str = "member"
) -> OrgMember:
    member = OrgMember(org_id=org_id, identity_id=identity_id, role=role)
    db.add(member)
    await db.commit()
    await db.refresh(member)
    return member


async def list_members(db: AsyncSession, org_id: uuid.UUID) -> Sequence[OrgMember]:
    result = await db.execute(
        select(OrgMember).where(OrgMember.org_id == org_id).order_by(OrgMember.created_at)
    )
    return result.scalars().all()
