"""Seed utilities for initial data setup.""" import os import re from datetime import datetime from bson import ObjectId from .security import get_password_hash DEFAULT_ADMIN_EMAIL = "vadymsamoilenko@oliver.agency" async def seed_default_admin(db) -> None: """Ensure the default admin user exists and has the admin role. Looks up vadymsamoilenko@oliver.agency (case-insensitive). - If found with a non-admin role: promotes to admin. - If not found: creates a local-auth admin account. Password is read from DEFAULT_ADMIN_PASSWORD env var (fallback: ChangeMe123!). """ email_pattern = re.compile(f"^{re.escape(DEFAULT_ADMIN_EMAIL)}$", re.IGNORECASE) existing = await db.users.find_one({"email": email_pattern}) if existing: if existing.get("role") != "admin": await db.users.update_one( {"_id": existing["_id"]}, {"$set": {"role": "admin", "updated_at": datetime.utcnow()}}, ) print(f"✅ Promoted {DEFAULT_ADMIN_EMAIL} to admin role") else: print(f"✅ Default admin {DEFAULT_ADMIN_EMAIL} already exists") return password = os.environ.get("DEFAULT_ADMIN_PASSWORD", "ChangeMe123!") user_doc = { "_id": str(ObjectId()), "email": DEFAULT_ADMIN_EMAIL, "hashed_password": get_password_hash(password), "full_name": "Vadym Samoilenko", "role": "admin", "auth_provider": "local", "is_active": True, "created_at": datetime.utcnow(), "updated_at": datetime.utcnow(), } await db.users.insert_one(user_doc) print(f"✅ Created default admin: {DEFAULT_ADMIN_EMAIL}")