import asyncio
import bcrypt
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import AsyncSessionLocal, engine, Base
from app.models.models import User, UserRole

def get_password_hash(password: str):
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

async def seed_data():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async with AsyncSessionLocal() as session:
        from sqlalchemy import select
        result = await session.execute(select(User).where(User.username == "admin"))
        admin_exists = result.scalar_one_or_none()

        if not admin_exists:
            new_admin = User(
                username="admin",
                full_name="Super Admin Mac",
                hashed_password=get_password_hash("admin123"),
                role=UserRole.SUPER_ADMIN,
                is_active=True
            )
            session.add(new_admin)
            
            new_teknisi = User(
                username="teknisi1",
                full_name="Teknisi Lapangan 1",
                hashed_password=get_password_hash("teknisi123"),
                role=UserRole.TEKNISI,
                is_active=True
            )
            session.add(new_teknisi)
            
            await session.commit()
            print("✅ Data seed berhasil! User: admin (pw: admin123) & teknisi1 (pw: teknisi123)")
        else:
            print("⚠️ Data sudah ada, skipping seed.")

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