from contextlib import asynccontextmanager
import os
print("RUN_CREATE_TABLES =", os.getenv("RUN_CREATE_TABLES"))
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.database.database import Base, engine

load_dotenv()

# Import all models to register them with SQLAlchemy
from app.models.staff.staff_model import Staff, StaffStore
from app.models.staff.store_model import Chain, Store, StoreProductInventory
from app.models.staff.transaction_model import ChainTransaction
from app.models.listing.products import (
    Product, ProductCategory,
    ProductListing, ManagerDiscount, ChainProduct
)
from app.models.user.user_model import User, OTPVerification, TokenBlacklist, UserAddress
from app.models.user.favorite_model import UserFavorite
from app.models.user.order_model import UserOrder, UserOrderItem, Voucher
from app.models.user.subscription_model import SubscriptionPlan, UserSubscription
from app.models.activity_log import ActivityLog

from app.routers import api_router


RUN_CREATE_TABLES = os.getenv("RUN_CREATE_TABLES", "False").lower() == "true"


@asynccontextmanager
async def lifespan(app: FastAPI):
    if RUN_CREATE_TABLES:
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)

    yield


app = FastAPI(lifespan=lifespan)

# Add CORS middleware - Allow all origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allow all HTTP methods
    allow_headers=["*"],  # Allow all headers
)


@app.get("/up")
def server_up():
    return {"message": "Hello, FastApi Server is running and up..!"}


app.include_router(api_router)
