from datetime import date
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from modules.auth.supabase_bearer import SupabaseBearer
from modules.database.services.provisioning_service import ProvisioningService

router = APIRouter(prefix="/provisioning", tags=["Provisioning"])
auth = SupabaseBearer()


class ProvisionUserRequest(BaseModel):
    user_id: str


class ProvisionUserResponse(BaseModel):
    user_db_name: str
    worker_db_name: Optional[str]
    worker_type: Optional[str]


class ProvisionSchoolRequest(BaseModel):
    institute_id: str


class ProvisionSchoolResponse(BaseModel):
    db_name: str
    curriculum_db_name: str


@router.post("/users", response_model=ProvisionUserResponse)
def provision_user(payload: ProvisionUserRequest, token=Depends(auth)):
    """Ensure a user's Neo4j resources exist."""
    # Basic authorization: require matching subject or service role token
    if token.get('role') not in ('service_role', 'admin') and token.get('sub') != payload.user_id:
        raise HTTPException(status_code=403, detail="Forbidden")

    service = ProvisioningService()
    result = service.ensure_user(payload.user_id)
    return ProvisionUserResponse(**result)


@router.post("/schools", response_model=ProvisionSchoolResponse)
def provision_school(payload: ProvisionSchoolRequest, token=Depends(auth)):
    """Ensure a school's Neo4j resources exist."""
    if token.get('role') not in ('service_role', 'admin'):
        raise HTTPException(status_code=403, detail="Forbidden")

    service = ProvisioningService()
    result = service.ensure_school(payload.institute_id)
    return ProvisionSchoolResponse(db_name=result['db_name'], curriculum_db_name=result['curriculum_db_name'])
