from app.database import db
from app.auth import hash_password
import asyncio
import os

ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "1234")
ADMIN_FORCE_RESET = os.getenv("ADMIN_FORCE_RESET", "0").lower() in {"1", "true", "yes"}

async def crear_usuario_admin():
    existing = await db.users.find_one({"username": ADMIN_USERNAME})
    if existing:
        if ADMIN_FORCE_RESET:
            hashed = hash_password(ADMIN_PASSWORD)
            await db.users.update_one(
                {"_id": existing["_id"]},
                {"$set": {"password": hashed}}
            )
            print("[!] Password de admin actualizado por ADMIN_FORCE_RESET")
        else:
            print("[✓] Usuario admin ya existe")
        return

    hashed = hash_password(ADMIN_PASSWORD)
    await db.users.insert_one({
        "username": ADMIN_USERNAME,
        "password": hashed,
        "role": "admin"
    })
    print("[+] Usuario admin creado con éxito")
