Spaces:
Sleeping

File size: 3,223 Bytes
20ee727
d571584
 
20ee727
 
 
d571584
 
20ee727
 
 
 
 
 
 
d571584
20ee727
d571584
20ee727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d571584
20ee727
 
 
 
 
 
 
 
 
 
 
 
d571584
 
20ee727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d571584
 
 
20ee727
 
 
 
 
 
 
 
 
 
 
 
d571584
20ee727
 
 
 
d571584
 
20ee727
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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}