"""Seed the database with the default Oliver Team and admin user."""
import asyncio
import uuid
from datetime import datetime, timezone

from sqlmodel import select
from services.database import async_session_maker

# Import all models so SQLAlchemy resolves FK references
from models.sql.client import ClientModel  # noqa: F401
from models.sql.user import UserModel
from models.sql.team import TeamModel
from models.sql.team_membership import TeamMembershipModel


async def seed():
    async with async_session_maker() as session:
        # --- Oliver Team ---
        result = await session.execute(
            select(TeamModel).where(TeamModel.is_default == True)  # noqa: E712
        )
        oliver_team = result.scalar_one_or_none()

        if oliver_team:
            print(f"Oliver Team already exists (id: {oliver_team.id})")
        else:
            oliver_team = TeamModel(
                id=uuid.uuid4(),
                name="Oliver Team",
                client_id=None,
                is_default=True,
                created_at=datetime.now(timezone.utc),
            )
            session.add(oliver_team)
            await session.flush()
            print(f"Created Oliver Team with id: {oliver_team.id}")

        # --- Admin user ---
        admin_email = "admin@deckforge.dev"
        result = await session.execute(
            select(UserModel).where(UserModel.email == admin_email)
        )
        admin_user = result.scalar_one_or_none()

        if admin_user:
            if admin_user.role != "super_admin":
                admin_user.role = "super_admin"
                session.add(admin_user)
                print(f"Updated {admin_email} role to super_admin")
            else:
                print(f"Admin user already exists (id: {admin_user.id})")
        else:
            admin_user = UserModel(
                email=admin_email,
                display_name="Admin",
                role="super_admin",
                is_active=True,
                created_at=datetime.now(timezone.utc),
                updated_at=datetime.now(timezone.utc),
            )
            session.add(admin_user)
            await session.flush()
            print(f"Created admin user with id: {admin_user.id}")

            # Add to Oliver Team
            membership = TeamMembershipModel(
                user_id=admin_user.id,
                team_id=oliver_team.id,
                assigned_at=datetime.now(timezone.utc),
            )
            session.add(membership)

        await session.commit()
        print("Seed complete.")


if __name__ == "__main__":
    asyncio.run(seed())
