from datetime import datetime
from os import getenv
from typing import Optional

from fastapi import FastAPI
import strawberry
from strawberry.asgi import GraphQL
from sqlmodel import create_engine, SQLModel

from api.models import PostQL
from api.crud import create_post, get_posts

ENGINE = create_engine(getenv("DATABASE_URL"))


@strawberry.type
class Query:
    @strawberry.field
    def post(self, slug: Optional[str] = None) -> list[PostQL]:
        return get_posts(ENGINE, slug)


@strawberry.type
class Mutation:
    @strawberry.field
    def add_post(self, slug: str, title: str, content: str, published: bool) -> PostQL:
        return create_post(
            ENGINE,
            PostQL(
                slug=slug,
                title=title,
                content=content,
                published=published,
                published_at=datetime.now(),
            ),
        )


schema = strawberry.Schema(query=Query, mutation=Mutation)

SQLModel.metadata.create_all(ENGINE)

graphql_app = GraphQL(schema)

app = FastAPI()
app.add_route("/graphql", graphql_app)
app.add_websocket_route("/graphql", graphql_app)

strawberry.asgi.GraphQL api.crud.get_posts sqlmodel.SQLModel.metadata.create_all strawberry.Schema datetime.datetime.now os.getenv fastapi.FastAPI
[((908, 957), 'strawberry.Schema', 'strawberry.Schema', ([], {'query': 'Query', 'mutation': 'Mutation'}), '(query=Query, mutation=Mutation)\n', (925, 957), False, 'import strawberry\n'), ((959, 995), 'sqlmodel.SQLModel.metadata.create_all', 'SQLModel.metadata.create_all', (['ENGINE'], {}), '(ENGINE)\n', (987, 995), False, 'from sqlmodel import create_engine, SQLModel\n'), ((1011, 1026), 'strawberry.asgi.GraphQL', 'GraphQL', (['schema'], {}), '(schema)\n', (1018, 1026), False, 'from strawberry.asgi import GraphQL\n'), ((1034, 1043), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (1041, 1043), False, 'from fastapi import FastAPI\n'), ((307, 329), 'os.getenv', 'getenv', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (313, 329), False, 'from os import getenv\n'), ((464, 487), 'api.crud.get_posts', 'get_posts', (['ENGINE', 'slug'], {}), '(ENGINE, slug)\n', (473, 487), False, 'from api.crud import create_post, get_posts\n'), ((856, 870), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (868, 870), False, 'from datetime import datetime\n')]