from fastapi.testclient import TestClient
from datetime import datetime, timedelta
from sqlalchemy import create_engine
from dotenv import load_dotenv
import pytz

from db import models
from main import app
import os

client = TestClient(app)

load_dotenv()
user = os.getenv('MYSQL_USER')
password = os.getenv('MYSQL_PASSWORD')
host = os.getenv('DB_HOST')
port = os.getenv('DB_PORT')
database = os.getenv('MYSQL_DATABASE')

SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}?charset=utf8"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
models.Base.metadata.create_all(bind=engine)


test = {
    "restaurant": {
        "place": "restaurant test",
        "day": datetime.now().weekday(),
        "open_time": datetime.now(tz=pytz.timezone("Europe/Paris")).strftime("%H:%M:%S"),
        "close_time": (datetime.now(tz=pytz.timezone("Europe/Paris")) + timedelta(hours=1)).strftime("%H:%M:%S")
    },
    "news": {
        "title": "news test",
        "content": "content test",
        "end_date": (datetime.now(tz=pytz.timezone("Europe/Paris")) + timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%S"),
        "place": "restaurant test"
    },
}


def test_post_opening_hours():
    response = client.post(
        "/api/opening_hours",
        headers={"accept": "application/json", "Content-Type": "application/json"},
        json=test["restaurant"],
    )
    assert response.status_code == 200
    assert response.json()["place"] == test["restaurant"]["place"]


def test_get_restaurants():
    response = client.get("/api/restaurants")
    assert response.status_code == 200
    assert len(response.json()) == 1
    assert response.json()[0]["name"] == test["restaurant"]["place"]
    assert response.json()[0]["status"]


def test_post_news_not_admin():
    response = client.post(
        "/api/news",
        headers={"Content-Type": "application/json", "Cookie": "connect_id=wrong_cookie"},
        json=test["news"],
    )
    assert response.status_code != 200
    assert response.json() == {"detail": "Invalid cookie"}
