from fastapi.exceptions import HTTPException
from sfm.models import Project, WorkItem
from sqlmodel import Session, select
from opencensus.ext.azure.log_exporter import AzureLogHandler
from sfm.config import get_settings
from sfm.logger import create_logger
from sfm.utils import (
    create_project_auth_token,
    hash_project_auth_token,
    verify_admin_key,
)

app_settings = get_settings()


logger = create_logger(__name__)


def get_all(db: Session, skip: int = None, limit: int = None):
    """Get all the projects and return them."""
    projects = db.exec(
        select(Project).order_by(Project.id).offset(skip).limit(limit)
    ).all()
    if not projects:
        logger.debug("Projects not found")
        raise HTTPException(status_code=404, detail="Projects not found")
    return projects


def get_by_id(db: Session, project_id: int):
    """Get the project with corresponding id and return it."""
    project = db.get(Project, project_id)
    if not project:
        logger.debug("Projects not found")
        raise HTTPException(status_code=404, detail="Project not found")
    return project


def create_project(db: Session, project_data, admin_key):
    """Take data from request and create a new project in the database."""
    project_name_repeat = db.exec(
        