import contextlib
import os
import pathlib

import hypothesis.strategies as st
import pytest
import strawberry
from hypothesis.strategies import SearchStrategy
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, SQLModel, create_engine
from starlette.testclient import TestClient

from fastapi_server.database.database import get_session
from fastapi_server.main import app
from fastapi_server.routes.graphql import schema

TEST_DB_FILE_PATH = 'test.db'
TEST_DB_URL = f'sqlite:///{TEST_DB_FILE_PATH}'
TEST_DB_MEMORY_PATH = ':memory:'
TEST_DB_MEMORY_URL = f'sqlite:///{TEST_DB_MEMORY_PATH}'


class BaseTest:
    method_client: TestClient = None  # type: ignore
    method_session: Session = None  # type: ignore
    example_client: TestClient = None  # type: ignore
    example_session: Session = None  # type: ignore

    def setup_method(self, _method):
        BaseTest.method_session = BaseTest.create_memory_sesssion()
        # BaseTest.method_session = BaseTest.create_file_sesssion()
        BaseTest.method_client = TestClient(app)
        BaseTest.method_client.app.dependency_overrides[get_session] = BaseTest.method_get_session

    def teardown_method(self, _method):
        if BaseTest.method_session is not None:
            db_path = pathlib.Path(TEST_DB_FILE_PATH)
            # Remove file if it wasnt a memory database
            if BaseTest.method_session.bind.url.database != TEST_DB_MEMORY_PATH and db_path.is_file():
                os.remove(db_path)
            BaseTest.method_session.close()
            BaseTest.method_session = None
        app.dependency_overrides.clear()
        BaseTest.method_client = None

    @classmethod
    def create_file_sesssion(cls):
        engine = create_engine(TEST_DB_URL, connect_args={'check_same_thread': False}, poolclass=StaticPool)
        