from test_main import *
import pytest
from datetime import datetime
from bson import ObjectId
from app.routes.auth import users_collection

@pytest.mark.order(3)
def test_set_user_admin():
    # Mettre à jour l'utilisateur testuser2 pour le rendre admin
    users_collection.update_one(
        {"username": "testuser2"},
        {"$set": {"is_admin": True}}
    )
    
    # Vérifier que la mise à jour a bien été effectuée
    user = users_collection.find_one({"username": "testuser2"})
    assert user is not None
    assert user["is_admin"] is True

def test_get_stats_unauthorized():
    response = client.get("/admin/stats")
    assert response.status_code == 401

def test_get_stats(token_second):
    response = client.get("/admin/stats", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 200
    data = response.json()
    
    # Vérifier la structure des statistiques
    assert "general" in data
    assert "last_30_days" in data
    assert "top_users" in data
    assert "top_shared_pins" in data
    
    # Vérifier les champs généraux
    assert "total_users" in data["general"]
    assert "total_pins" in data["general"]
    assert "total_images" in data["general"]
    assert "total_friends" in data["general"]
    assert "total_storage_bytes" in data["general"]
    
    # Vérifier les statistiques des 30 derniers jours
    assert "new_users" in data["last_30_days"]
    assert "new_pins" in data["last_30_days"]
    assert "new_images" in data["last_30_days"]

def test_get_config_unauthorized():
    response = client.get("/admin/config")
    assert response.status_code == 401

def test_get_config(token_second):
    response = client.get("/admin/config", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 200
    data = response.json()
    
    # Vérifier les champs de configuration
    assert "max_image_size" in data
    assert "max_images_per_pin" in data
    assert "max_images_per_user" in data
    assert "allowed_image_types" in data
    assert "max_pins_per_user" in data
    assert "max_friends_per_user" in data

def test_update_config_unauthorized():
    new_config = {
        "max_image_size": 5000000,
        "max_images_per_pin": 5,
        "max_images_per_user": 100,
        "allowed_image_types": ["image/jpeg", "image/png"],
        "max_pins_per_user": 50,
        "max_friends_per_user": 200
    }
    response = client.patch("/admin/config", json=new_config)
    assert response.status_code == 401

def test_update_config(token_second):
    new_config = {
        "max_image_size": 5000000,
        "max_images_per_pin": 5,
        "max_images_per_user": 100,
        "allowed_image_types": ["image/jpeg", "image/png"],
        "max_pins_per_user": 50,
        "max_friends_per_user": 200
    }
    response = client.patch("/admin/config", json=new_config, headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 200
    data = response.json()
    assert data == new_config

def test_list_users_unauthorized():
    response = client.get("/admin/users")
    assert response.status_code == 401

def test_list_users(token_second):
    response = client.get("/admin/users", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 200
    data = response.json()
    assert isinstance(data, list)
    # Vérifier que la liste contient au moins l'utilisateur testuser2
    assert any(user["username"] == "testuser2" for user in data)

def test_delete_user_unauthorized():
    response = client.delete("/admin/user/123")
    assert response.status_code == 401

def test_delete_user_invalid_uid(token_second):
    response = client.delete("/admin/user/invalid_uid", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 400

def test_delete_user_not_found(token_second):
    # Utiliser un ID qui n'existe probablement pas
    non_existent_id = "507f1f77bcf86cd799439011"
    response = client.delete(f"/admin/user/{non_existent_id}", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 404

def test_delete_user(token_second):
    # D'abord, créer un utilisateur à supprimer
    response = client.post("/register", json={"username": "user_to_delete", "password": "password123"})
    assert response.status_code == 200
    user_id = response.json()["user_id"]
    
    # Ensuite, supprimer cet utilisateur
    response = client.delete(f"/admin/user/{user_id}", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 200
    assert response.json()["message"] == "Utilisateur supprimé avec succès"
    
    # Vérifier que l'utilisateur n'existe plus
    response = client.get(f"/user/{user_id}", headers={"Authorization": f"Bearer {token_second}"})
    assert response.status_code == 404 