import uuid

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

from domains.groups.models import Group, GroupMember

async def create_group(db: AsyncSession, group: Group):
    db.add(group)
    await db.commit()
    await db.refresh(group)
    return group


async def get_group_by_id(db: AsyncSession, group_id: uuid.UUID):
    result = await db.execute(
        select(Group).where(Group.id == group_id)
    )
    return result.scalar_one_or_none()

async def add_group_member(db: AsyncSession, membership: GroupMember):
    db.add(membership)
    await db.commit()
    return membership


async def get_user_groups(db: AsyncSession, user_id: uuid.UUID):
    result = await db.execute(
        select(Group)
        .join(GroupMember)
        .where(GroupMember.user_id == user_id)
    )
    return result.scalars().all()


async def get_groups_by_type(db: AsyncSession, group_type):
    result = await db.execute(
        select(Group).where(Group.type == group_type)
    )
    return result.scalars().all()


async def get_all_groups(db: AsyncSession):
    result = await db.execute(select(Group))
    return result.scalars().all()


async def get_group_members_with_details(db: AsyncSession, group_id: uuid.UUID):
    from domains.users.models import User
    result = await db.execute(
        select(GroupMember, User.username)
        .join(User, GroupMember.user_id == User.id)
        .where(GroupMember.group_id == group_id)
    )
    return result.all()


async def get_group_member(db: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID):
    result = await db.execute(
        select(GroupMember)
        .where(GroupMember.group_id == group_id)
        .where(GroupMember.user_id == user_id)
    )
    return result.scalar_one_or_none()


async def delete_group_member(db: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID):
    from sqlalchemy import delete
    await db.execute(
        delete(GroupMember)
        .where(GroupMember.group_id == group_id)
        .where(GroupMember.user_id == user_id)
    )
    await db.commit()

async def delete_group(db: AsyncSession, group_id: uuid.UUID):
    from sqlalchemy import delete
    await db.execute(
        delete(Group)
        .where(Group.id == group_id)
    )
    await db.commit()
