"""Create demo admin users for both tenants."""
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy import text
import bcrypt as _bcrypt

def hash_password(pw: str) -> str:
    return _bcrypt.hashpw(pw.encode(), _bcrypt.gensalt()).decode()

TENANT_SLUGS = ["demo-enterprise", "demo-government"]


async def create_users():
    engine = create_async_engine("postgresql+asyncpg://ams:ams_dev_password@db:5432/ams", echo=False)
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with Session() as session:
        for slug in TENANT_SLUGS:
            # Tenant IDs are randomly generated by seed.py (uuid.uuid4()), not
            # fixed — a hardcoded ID list here silently drifted from the real
            # seeded tenant and wrote the admin user into a schema for a tenant
            # that didn't exist, leaving the real one (e.g. demo-government)
            # fully migrated but with zero users. Look it up by slug instead.
            row = (await session.execute(
                text("SELECT id::text FROM public.tenants WHERE slug = :slug"),
                {"slug": slug},
            )).fetchone()
            if not row:
                print(f"  SKIP {slug}: no tenant row found in public.tenants — run seed.py first")
                continue
            tid = row.id
            schema = "tenant_" + tid.replace("-", "_")
            await session.execute(text(f"SET search_path TO {schema}, public"))
            pw_hash = hash_password("demo1234")
            user_row = (await session.execute(
                text("""
                    INSERT INTO users (id, email, password_hash, name, role, is_active, created_at, updated_at)
                    VALUES (gen_random_uuid(), :email, :pw, :name, :role, true, NOW(), NOW())
                    ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email
                    RETURNING id::text
                """),
                {"email": f"admin@{slug}.in", "pw": pw_hash, "name": "Admin User", "role": "super_admin"},
            )).fetchone()

            # The `role` column above drives the JWT/permission checks, but the
            # "Users Assigned" count on Role Management reads a separate table
            # (user_role_assignments) — this raw seed script used to skip it
            # entirely, so even the seeded super_admin showed 0 assigned users.
            role_row = (await session.execute(
                text("SELECT id::text FROM roles WHERE name = 'super_admin'")
            )).fetchone()
            if user_row and role_row:
                exists = (await session.execute(
                    text("SELECT 1 FROM user_role_assignments WHERE user_id = :u AND role_id = :r"),
                    {"u": user_row.id, "r": role_row.id},
                )).fetchone()
                if not exists:
                    await session.execute(
                        text("INSERT INTO user_role_assignments (id, user_id, role_id) VALUES (gen_random_uuid(), :u, :r)"),
                        {"u": user_row.id, "r": role_row.id},
                    )
            print(f"  User admin@{slug}.in created")
        await session.commit()
        print("Done.")
    await engine.dispose()


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