import pytest
from tests.conftest import TEST_SECRET_KEY, TEST_REFRESH_TOKEN_EXPIRY_DAYS
import os
from werkzeug.security import generate_password_hash

from flask import Flask
from api.penalty_api import penalty_api
from api.auth_api import auth_api
from db.db import task_db, child_db, users_db
from tinydb import Query


TEST_EMAIL = "testuser@example.com"
TEST_PASSWORD = "testpass"

def add_test_user():
    users_db.remove(Query().email == TEST_EMAIL)
    users_db.insert({
        "id": "testuserid",
        "first_name": "Test",
        "last_name": "User",
        "email": TEST_EMAIL,
        "password": generate_password_hash(TEST_PASSWORD),
        "verified": True,
        "image_id": "boy01"
    })

def login_and_set_cookie(client):
    resp = client.post('/auth/login', json={"email": TEST_EMAIL, "password": TEST_PASSWORD})
    assert resp.status_code == 200

@pytest.fixture
def client():
    app = Flask(__name__)
    app.register_blueprint(penalty_api)
    app.register_blueprint(auth_api, url_prefix='/auth')
    app.config['TESTING'] = True
    app.config['SECRET_KEY'] = TEST_SECRET_KEY
    app.config['REFRESH_TOKEN_EXPIRY_DAYS'] = TEST_REFRESH_TOKEN_EXPIRY_DAYS
    with app.test_client() as client:
        add_test_user()
        login_and_set_cookie(client)
        yield client


def test_add_penalty(client):
    task_db.truncate()
    response = client.put('/penalty/add', json={'name': 'Fighting', 'points': 10})
    assert response.status_code == 201
    tasks = task_db.all()
    assert any(t.get('name') == 'Fighting' and t.get('type') == 'penalty' for t in tasks)


def test_list_penalties(client):
    task_db.truncate()
    task_db.insert({'id': 'p1', 'name': 'Yelling', 'points': 5, 'type': 'penalty', 'user_id': 'testuserid'})
    task_db.insert({'id': 'c1', 'name': 'Chore', 'points': 3, 'type': 'chore', 'user_id': 'testuserid'})
    response = client.get('/penalty/list')
    assert response.status_code == 200
    data = response.get_json()
    assert len(data['tasks']) == 1
    assert data['tasks'][0]['id'] == 'p1'


def test_edit_penalty(client):
    task_db.truncate()
    task_db.insert({'id': 'p_edit', 'name': 'Old', 'points': 5, 'type': 'penalty', 'user_id': 'testuserid'})
    response = client.put('/penalty/p_edit/edit', json={'name': 'New Penalty', 'points': 20})
    assert response.status_code == 200
    data = response.get_json()
    assert data['name'] == 'New Penalty'
    assert data['points'] == 20


def test_delete_penalty(client):
    task_db.truncate()
    child_db.truncate()
    task_db.insert({'id': 'p_del', 'name': 'Del Pen', 'points': 5, 'type': 'penalty', 'user_id': 'testuserid'})
    child_db.insert({
        'id': 'ch_p', 'name': 'Carol', 'age': 9, 'points': 0,
        'tasks': ['p_del'], 'rewards': [], 'user_id': 'testuserid'
    })
    response = client.delete('/penalty/p_del')
    assert response.status_code == 200
    child = child_db.get(Query().id == 'ch_p')
    assert 'p_del' not in child.get('tasks', [])
