from fastapi import APIRouter, Depends, HTTPException, Request from sqlmodel.ext.asyncio.session import AsyncSession from sqlmodel import select from datetime import datetime from uuid import UUID from app.api.deps import get_current_user from app.core.database import get_async_session from app.services.google_calendar import get_google_calendar_service from app.models.tenant import Tenant from app.models.user import User router = APIRouter() @router.get("/connect") async def connect_calendar( request: Request, session: AsyncSession = Depends(get_async_session), current_user: User = Depends(get_current_user), redirect_uri: str = None ): """ Start the OAuth flow for the current user's tenant. Returns the Google Auth URL. """ if current_user.role != "OWNER": raise HTTPException(status_code=403, detail="Only owners can connect calendar") tenant_id = current_user.tenant_id service = get_google_calendar_service() # We pass tenant_id as state auth_url = service.get_auth_url(tenant_id, redirect_uri) return {"url": auth_url} @router.get("/callback") async def callback( code: str, state: str, request: Request, session: AsyncSession = Depends(get_async_session) # Note: No user auth here usually, as it's a redirect from Google. # State contains tenant_id. ): """ Handle Google OAuth callback. Exchange code for tokens and store in Tenant. """ try: tenant_id = UUID(state) except ValueError: raise HTTPException(status_code=400, detail="Invalid state parameter") result = await session.execute(select(Tenant).where(Tenant.id == tenant_id)) tenant = result.scalar_one_or_none() if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") service = get_google_calendar_service() # The pure redirect_uri used in the flow must match exactly. # If frontend sent a custom one, we need to know it here too? # Usually we use a fixed config one or extract from request base url. # For now, let's assume default from service. try: tokens = await service.authenticate(code) # Merge with existing config or create new # We store the whole token dict tenant.google_calendar_config = tokens session.add(tenant) await session.commit() await session.refresh(tenant) return {"status": "success", "message": "Google Calendar connected"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @router.get("/availability") async def check_availability( start_time: datetime, end_time: datetime, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_async_session) ): """ Check availability directly from Google Calendar for debugging. """ result = await session.execute(select(Tenant).where(Tenant.id == current_user.tenant_id)) tenant = result.scalar_one_or_none() service = get_google_calendar_service() slots = await service.list_free_slots(tenant, start_time, end_time) return {"busy": slots}