import pytest
import json
import os
from .helpers import ensure_clean_session


class TestAdminFunctions:
    """Test administrative functions."""

    def test_admin_dashboard(self, logged_in_client):
        """Test accessing admin dashboard."""
        # Ensure we have a clean, authenticated session
        logged_in_client = ensure_clean_session(logged_in_client)

        # Access the admin dashboard
        response = logged_in_client.get("/admin/dashboard")

        assert response.status_code == 200
        assert b"Administraci" in response.data or b"Dashboard" in response.data

    def test_filetypes_management(self, logged_in_client):
        """Test file types management page."""
        response = logged_in_client.get("/admin/filetypes")
        assert response.status_code == 200
        assert b"Tipos de Archivo" in response.data

    def test_system_status(self, logged_in_client):
        """Test system status page."""
        response = logged_in_client.get("/admin/system")
        assert response.status_code == 200
        assert b"Estado del Sistema" in response.data

    def test_add_filetype(self, logged_in_client, app):
        """Test adding a new file type."""
        response = logged_in_client.post(
            "/admin/filetypes/add",
            data={
                "extension": "docx",
                "descripcion": "Documento Word",
                "mime_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "tamano_maximo": 15728640,  # 15MB in bytes
            },
            follow_redirects=True,
        )

        assert response.status_code == 200

        # Verify file type was added
        with app.app_context():
            filetypes_path = os.path.join(
                app.config["STORAGE_PATH"], "filetypes", "filetypes.json"
            )
            with open(filetypes_path, "r") as f:
                filetypes = json.load(f)
                assert "docx" in filetypes
                assert filetypes["docx"]["descripcion"] == "Documento Word"

    def test_delete_filetype(self, logged_in_client, app):
        """Test deleting a file type."""
        # First add a file type to delete
        logged_in_client.post(
            "/admin/filetypes/add",
            data={
                "extension": "xlsx",
                "descripcion": "Hoja de cálculo Excel",
                "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "tamano_maximo": 15728640,
            },
            follow_redirects=True,
        )

        # Verify it was added
        with app.app_context():
            filetypes_path = os.path.join(
                app.config["STORAGE_PATH"], "filetypes", "filetypes.json"
            )
            with open(filetypes_path, "r") as f:
                filetypes = json.load(f)
                assert "xlsx" in filetypes

        # Now delete it
        response = logged_in_client.post(
            "/admin/filetypes/xlsx/delete", follow_redirects=True
        )
        assert response.status_code == 200

        # Verify it was deleted
        with app.app_context():
            filetypes_path = os.path.join(
                app.config["STORAGE_PATH"], "filetypes", "filetypes.json"
            )
            with open(filetypes_path, "r") as f:
                filetypes = json.load(f)
                assert "xlsx" not in filetypes

    def test_update_filetype(self, logged_in_client, app):
        """Test updating a file type."""
        # First add a file type to update
        logged_in_client.post(
            "/admin/filetypes/add",
            data={
                "extension": "png",
                "descripcion": "Imagen PNG",
                "mime_type": "image/png",
                "tamano_maximo": 5242880,  # 5MB
            },
            follow_redirects=True,
        )

        # Now update it
        response = logged_in_client.post(
            "/admin/filetypes/png/update",
            data={
                "descripcion": "Imagen PNG Actualizada",
                "mime_type": "image/png",
                "tamano_maximo": 10485760,  # 10MB (increased)
            },
            follow_redirects=True,
        )

        assert response.status_code == 200

        # Verify changes
        with app.app_context():
            filetypes_path = os.path.join(
                app.config["STORAGE_PATH"], "filetypes", "filetypes.json"
            )
            with open(filetypes_path, "r") as f:
                filetypes = json.load(f)
                assert "png" in filetypes
                assert filetypes["png"]["descripcion"] == "Imagen PNG Actualizada"
                assert filetypes["png"]["tamano_maximo"] == 10485760
