import logging
import sys

import uvicorn
from fastapi import FastAPI
from pyrate_limiter import Rate, Limiter, Duration

from service import auth_service
from service.tray_order_service import TrayOrderService
from service.product_service import ProductService
from db.helpers import drop_tables, create_tables
from service.webhook_service import process_webhook

app = FastAPI()

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)

logger = logging.getLogger(__name__)
# db_helpers.drop_tables()
# db_helpers.create_tables()

@app.get("/get-tray")
def read_root():
    access_token = auth_service.refresh_access_token()
    rate = Rate(100, Duration.SECOND * 60)
    limiter = Limiter(rate, max_delay=50000)
    order_service = TrayOrderService(access_token, limiter)
    product_service = ProductService(access_token, limiter)

    categories = product_service.save_all_categories()
    products = product_service.save_all_products()
    orders = order_service.save_all_orders()
    products_sold = product_service.save_all_products_sold()
    return 200


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/handle-webhook")
def handle_webhook(body: dict):
    logger.info(body)    
    return process_webhook(body=body)

@app.post("/drop_tables")
def drop():
    drop_tables()
    return 200
    
@app.post("/create_tables")
def create():
    create_tables()
    return 200

@app.get("/get_auth_token")
def get_auth_token():
    return auth_service.get_auth_token()

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