# services/tenant/app/main.py
"""
Tenant Service FastAPI application - FIXED VERSION
"""

import structlog
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.core.config import settings
from app.core.database import database_manager
from app.api import tenants, subscriptions
from shared.monitoring.logging import setup_logging
from shared.monitoring.metrics import MetricsCollector

# Setup logging
setup_logging("tenant-service", settings.LOG_LEVEL)
logger = structlog.get_logger()

# Create FastAPI app
app = FastAPI(
    title="Tenant Management Service",
    description="Multi-tenant bakery management service",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# Initialize metrics
metrics_collector = MetricsCollector("tenant_service")
app.state.metrics_collector = metrics_collector

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(tenants.router, prefix="/api/v1", tags=["tenants"])
app.include_router(subscriptions.router, prefix="/api/v1", tags=["subscriptions"])

@app.on_event("startup")
async def startup_event():
    """Initialize service on startup"""
    logger.info("Starting Tenant Service...")
    
    try:
        # ✅ FIX: Import models to ensure they're registered with SQLAlchemy
        from app.models.tenants import Tenant, TenantMember, Subscription
        logger.info("Tenant models imported successfully")
        
        # ✅ FIX: Create database tables on startup
        await database_manager.create_tables()
        logger.info("Tenant database tables created successfully")
        
    except Exception as e:
        logger.error(f"Failed to initialize tenant service: {e}")
        raise
    
    logger.info("Tenant Service startup completed successfully")

@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown"""
    logger.info("Shutting down Tenant Service...")
    
    try:
        # Close database connections properly
        if hasattr(database_manager, 'engine') and database_manager.engine:
            await database_manager.engine.dispose()
            logger.info("Database connections closed")
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")
    
    logger.info("Tenant Service shutdown completed")

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "service": "tenant-service",
        "version": "1.0.0"
    }

@app.get("/metrics")
async def metrics():
    """Prometheus metrics endpoint"""
    return metrics_collector.get_metrics()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)