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.kindness_api import kindness_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(kindness_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_kindness(client):
    task_db.truncate()
    response = client.put('/kindness/add', json={'name': 'Helped Sibling', 'points': 5})
    assert response.status_code == 201
    tasks = task_db.all()
    assert any(t.get('name') == 'Helped Sibling' and t.get('type') == 'kindness' for t in tasks)


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


def test_edit_kindness(client):
    task_db.truncate()
    task_db.insert({'id': 'k_edit', 'name': 'Old', 'points': 5, 'type': 'kindness', 'user_id': 'testuserid'})
    response = client.put('/kindness/k_edit/edit', json={'name': 'New Kind'})
    assert response.status_code == 200
    data = response.get_json()
    assert data['name'] == 'New Kind'


def test_delete_kindness(client):
    task_db.truncate()
    child_db.truncate()
    task_db.insert({'id': 'k_del', 'name': 'Del Kind', 'points': 5, 'type': 'kindness', 'user_id': 'testuserid'})
    child_db.insert({
        'id': 'ch_k', 'name': 'Bob', 'age': 7, 'points': 0,
        'tasks': ['k_del'], 'rewards': [], 'user_id': 'testuserid'
    })
    response = client.delete('/kindness/k_del')
    assert response.status_code == 200
    child = child_db.get(Query().id == 'ch_k')
    assert 'k_del' not in child.get('tasks', [])
