import pytest
import os
from flask import Flask
from api.reward_api import reward_api
from db.db import reward_db, child_db
from tinydb import Query
from models.reward import Reward

@pytest.fixture
def client():
    app = Flask(__name__)
    app.register_blueprint(reward_api)
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

@pytest.fixture(scope="session", autouse=True)
def cleanup_db():
    yield
    reward_db.close()
    if os.path.exists('rewards.json'):
        os.remove('rewards.json')

def test_add_reward(client):
    response = client.put('/reward/add', json={'name': 'Vacation', 'cost': 10, 'description': "A test reward"})
    assert response.status_code == 201
    assert b'Reward Vacation added.' in response.data
    # verify in database
    rewards = reward_db.all()
    assert any(reward.get('name') == 'Vacation' and reward.get('cost') == 10 and reward.get('description') == "A test reward" and reward.get('image_id') == '' for reward in rewards)

    response = client.put('/reward/add', json={'name': 'Ice Cream', 'cost': 4, 'description': "A test ice cream", 'image_id': 'ice_cream'})
    assert response.status_code == 201
    assert b'Reward Ice Cream added.' in response.data
    # verify in database
    rewards = reward_db.all()
    assert any(reward.get('name') == 'Ice Cream' and reward.get('cost') == 4 and reward.get('description') == "A test ice cream" and reward.get('image_id') == 'ice_cream' for reward in rewards)


def test_list_rewards(client):
    reward_db.truncate()
    reward_db.insert(Reward(name='Reward1', description='Desc1', cost=5).to_dict())
    reward_db.insert(Reward(name='Reward2', description='Desc2', cost=15, image_id='ice_cream').to_dict())
    response = client.get('/reward/list')
    assert response.status_code == 200
    assert b'rewards' in response.data
    data = response.json
    assert len(data['rewards']) == 2


def test_get_reward_not_found(client):
    response = client.get('/reward/nonexistent-id')
    assert response.status_code == 404
    assert b'Reward not found' in response.data

def test_delete_reward_not_found(client):
    response = client.delete('/reward/nonexistent-id')
    assert response.status_code == 404
    assert b'Reward not found' in response.data

def test_delete_assigned_reward_removes_from_child(client):
    # create task and child with the task already assigned
    reward_db.insert({'id': 'r_delete_assigned', 'name': 'Temp Task', 'cost': 5})
    child_db.insert({
        'id': 'child_for_reward_delete',
        'name': 'Frank',
        'age': 7,
        'points': 0,
        'rewards': ['r_delete_assigned'],
        'tasks': []
    })

    ChildQuery = Query()
    # precondition: child has the task
    assert 'r_delete_assigned' in child_db.search(ChildQuery.id == 'child_for_reward_delete')[0].get('rewards', [])

    # call the delete endpoint
    resp = client.delete('/reward/r_delete_assigned')
    assert resp.status_code == 200

    # verify the task id is no longer in the child's tasks
    child = child_db.search(ChildQuery.id == 'child_for_reward_delete')[0]
    assert 'r_delete_assigned' not in child.get('rewards', [])