
# app/commands/tenant_seed.py
from flask import current_app
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import click

from ..platform_models import Tenant
from ..cli import seed_all
from .. import db

def register_tenant_seed(app):
    @app.cli.command("seed-tenant")
    @click.option("--slug", required=True, help="Tenant slug (e.g. softec)")
    def seed_tenant(slug):
        # --- get tenant from PLATFORM DB ---
        platform_engine = db.get_engine(current_app, bind="platform")
        PlatformSession = sessionmaker(bind=platform_engine)

        with PlatformSession() as ps:
            tenant = ps.query(Tenant).filter_by(slug=slug, is_active=True).first()

        if not tenant:
            raise click.ClickException(f"Tenant not found in PLATFORM DB: {slug}")

        click.echo(f"Seeding tenant: {slug} -> {tenant.db_uri}")

        # --- temporarily force db.session to use TENANT engine ---
        tenant_engine = create_engine(tenant.db_uri, pool_pre_ping=True, pool_recycle=1800)

        # IMPORTANT: remove any existing session state and bind to tenant
        db.session.remove()
        db.session.configure(bind=tenant_engine)

        # run your standard seed
        seed_all()
        db.session.commit()

        # cleanup
        db.session.remove()
        click.echo("✅ Done.")