# https://fastapi.tiangolo.com/how-to/graphql/#graphql-with-strawberry

import typing
import strawberry
from strawberry.fastapi import GraphQLRouter
import database as db
from logger import get_logger
logger = get_logger(__name__)

def get_sites():
    conn = db.connect_to_db()
    try:
        with db.connect_to_db() as conn:
            sites = db.get_cellsites(conn)
            ql_list = []
            for site in sites:
                print(site)
                ql_list.append(
                    Cellsite(
                        id=site['id'],
                        lat=site['lat'],
                        lon=site['lon']
                    )
                )
            return ql_list
    except Exception as e:
        logger.error(f"Error fetching cellsite {id}: {e}", exc_info=True)
        return []
    finally:
        conn.close()

def get_incidents():
    conn = db.connect_to_db()
    try:
        with conn:
            incidents = db.get_incidents(conn)
            ql_list = []
            for incident in incidents:
                print(incident)
                ql_list.append(
                    Incident(
                        id=incident['id'],
                        text=incident['text'],
                        severity=incident['severity'],
                        status=incident['status'],
                        created_by=incident['created_by'],
                        site_id=incident['site_id']
                    )
                )
            return ql_list
    except Exception as e:
        logger.error(f"Error fetching cellsite {id}: {e}", exc_info=True)
        return []
    finally:
        conn.close()

@strawberry.type
class Cellsite:
    id: int
    lat: float
    lon: float

# TODO: Add incident and join with cellsite

# TODO: Query a site ID and get all related incidents
# TODO: Query an incident and get all related site id

@strawberry.type
class Incident:
    id: int
    text: str
    severity: int
    status: str
    created_by: str
    # site_id: typing.List[Cellsite]
    site_id: int

@strawberry.type
class Query:
    cellsites: typing.List[Cellsite] = strawberry.field(resolver=get_sites)
    incidents: typing.List[Incident] = strawberry.field(resolver=get_incidents)



schema = strawberry.Schema(query=Query)

graphql_app = GraphQLRouter(schema)
