"""Create or reset a default admin user for local MySQL seeding."""

import asyncio
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from sqlalchemy import update

from app.core.database import close_database_connection, connect_to_database, get_session_factory
from app.core.security import hash_password
from app.domain.entities.user_registration import UserRegistration
from app.infrastructure.db.models import UserRegistrationModel
from app.infrastructure.repositories.user_registration_mysql_repository import MySQLUserRegistrationRepository


async def seed(
    username: str = "asim",
    email: str = "asim.shabbir@gmail.com",
    full_name: str = "Asim Shabbir",
    password: str = "Password123!",
) -> None:
    await connect_to_database()
    factory = get_session_factory()

    async with factory() as session:
        repo = MySQLUserRegistrationRepository(session)
        existing = await repo.get_by_email(email)
        password_hash = hash_password(password)

        if existing:
            await session.execute(
                update(UserRegistrationModel)
                .where(UserRegistrationModel.id == existing.id)
                .values(password_hash=password_hash, is_active=True)
            )
            await session.commit()
            print(f"Reset password for: {existing.username} ({existing.email}) id={existing.id}")
            print(f"Password: {password}")
        else:
            user = UserRegistration(
                username=username,
                email=email,
                full_name=full_name,
                password_hash=password_hash,
                is_active=True,
            )
            created = await repo.create(user)
            print(f"Created user: {created.username} ({created.email}) id={created.id}")
            print(f"Password: {password}")

    await close_database_connection()


if __name__ == "__main__":
    asyncio.run(seed())
