import graphene
from db import get_dynamic_connection
from .types import Scheduler, PaginatedScheduler, Season, Division
from .helpers import _resolve_game

class Query(graphene.ObjectType):
    scheduler = graphene.Field(
        Scheduler,
        id=graphene.Int(required=True),
        description="Get a single scheduler entry by ID. Mirrors SchedulerQuery."
    )
    schedulers = graphene.Field(
        PaginatedScheduler,
        limit=graphene.Int(default_value=100),
        page=graphene.Int(default_value=1),
        description="List all scheduler entries (paginated). Mirrors SchedulersQuery."
    )
    seasons = graphene.List(Season, description="Get the list of seasons in ascending order.")
    divisions = graphene.List(Division, description="Get the list of divisions in ascending order.")

    def resolve_scheduler(self, info, id):
        db_name = info.context["db_name"]
        with get_dynamic_connection(db_name) as conn:
            return _resolve_game(conn, id)

    def resolve_schedulers(self, info, limit, page):
        db_name = info.context["db_name"]
        with get_dynamic_connection(db_name) as conn:
            with conn.cursor() as cur:
                # Total count
                cur.execute("SELECT COUNT(*) AS cnt FROM game")
                total = cur.fetchone()["cnt"]

                offset = (page - 1) * limit
                cur.execute(
                    "SELECT id FROM game ORDER BY id LIMIT %s OFFSET %s",
                    (limit, offset),
                )
                rows = cur.fetchall()

            items = [_resolve_game(conn, row["id"]) for row in rows]

        return PaginatedScheduler(
            data=items, total=total, page=page, per_page=limit
        )

    def resolve_seasons(self, info):
        db_name = info.context["db_name"]
        with get_dynamic_connection(db_name) as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "SELECT season_id, season_desc, year_id FROM season ORDER BY season_id ASC"
                )
                rows = cur.fetchall()
        return [
            Season(
                season_id=row["season_id"],
                season_desc=row["season_desc"],
                year_id=row["year_id"],
            )
            for row in rows
        ]

    def resolve_divisions(self, info):
        db_name = info.context["db_name"]
        with get_dynamic_connection(db_name) as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "SELECT id, description FROM level ORDER BY id ASC"
                )
                rows = cur.fetchall()
        return [
            Division(
                division_id=row["id"],
                division_name=row["description"],
            )
            for row in rows
        ]
