"""
Chat service — system group bootstrap helpers.
"""
from datetime import datetime, timezone
from sqlalchemy.orm import Session

from models.chat import Conversation, ConversationParticipant
from models.user import User


def _utcnow() -> datetime:
    return datetime.now(timezone.utc)


def ensure_system_group(db: Session) -> Conversation:
    """
    Guarantee that the single system-wide 'Ομάδα' group conversation exists.
    If it is missing, create it and add all currently active users as participants.
    Returns the (possibly freshly created) Conversation.
    """
    existing = (
        db.query(Conversation)
        .filter(Conversation.is_system == True)  # noqa: E712
        .first()
    )
    if existing:
        return existing

    # Determine creator — first admin/manager user, or user id=1 as fallback
    creator = (
        db.query(User)
        .filter(User.perm_access_dashboard == True, User.is_active == True)  # noqa: E712
        .order_by(User.id)
        .first()
    )
    creator_id = creator.id if creator else 1

    conv = Conversation(
        type="group",
        name="Ομάδα",
        is_system=True,
        created_by=creator_id,
    )
    db.add(conv)
    db.flush()  # get conv.id before adding participants

    active_users = (
        db.query(User).filter(User.is_active == True).all()  # noqa: E712
    )
    now = _utcnow()
    for u in active_users:
        participant = ConversationParticipant(
            conversation_id=conv.id,
            user_id=u.id,
            joined_at=now,
        )
        db.add(participant)

    db.commit()
    db.refresh(conv)
    return conv


def add_user_to_system_group(db: Session, user_id: int) -> None:
    """
    Add a user to the system group if not already a participant.
    Safe to call even when the system group does not exist yet (it will be created).
    """
    conv = ensure_system_group(db)

    already = (
        db.query(ConversationParticipant)
        .filter(
            ConversationParticipant.conversation_id == conv.id,
            ConversationParticipant.user_id == user_id,
        )
        .first()
    )
    if already:
        return

    participant = ConversationParticipant(
        conversation_id=conv.id,
        user_id=user_id,
        joined_at=_utcnow(),
    )
    db.add(participant)
    db.commit()
