"""Tests for the ECP forms."""

from __future__ import annotations

from io import BytesIO
from typing import Any

import pytest
from django.core.files.uploadedfile import SimpleUploadedFile

from ecp_auth.forms import CertificateUploadForm, RegisterForm


class TestCertificateUploadForm:
    """Tests for the CertificateUploadForm."""

    def test_valid_form(self, pkcs12_data: bytes) -> None:
        """Test form with valid PKCS#12 file."""
        uploaded_file = SimpleUploadedFile(
            "test.p12", pkcs12_data, content_type="application/x-pkcs12"
        )
        form = CertificateUploadForm(
            data={"pkcs12_password": "testpassword"},
            files={"pkcs12_file": uploaded_file},
        )

        assert form.is_valid()

    def test_missing_file(self) -> None:
        """Test form without file."""
        form = CertificateUploadForm(data={}, files={})
        assert form.is_valid() is False

    def test_invalid_extension(self) -> None:
        """Test form with wrong file extension."""
        uploaded_file = SimpleUploadedFile(
            "test.txt", b"not a cert", content_type="text/plain"
        )
        form = CertificateUploadForm(
            data={},
            files={"pkcs12_file": uploaded_file},
        )

        assert form.is_valid() is False

    def test_file_too_large(self) -> None:
        """Test form with file exceeding size limit."""
        large_data = b"x" * (6 * 1024 * 1024)  # 6 MB
        uploaded_file = SimpleUploadedFile(
            "test.p12", large_data, content_type="application/x-pkcs12"
        )
        form = CertificateUploadForm(
            data={},
            files={"pkcs12_file": uploaded_file},
        )

        assert form.is_valid() is False


@pytest.mark.django_db
class TestRegisterForm:
    """Tests for the RegisterForm."""

    def test_valid_form(self, pkcs12_data: bytes) -> None:
        """Test form with valid data."""
        uploaded_file = SimpleUploadedFile(
            "test.p12", pkcs12_data, content_type="application/x-pkcs12"
        )
        form = RegisterForm(
            data={
                "username": "newuser",
                "email": "new@example.com",
                "pkcs12_password": "testpassword",
            },
            files={"pkcs12_file": uploaded_file},
        )

        assert form.is_valid()

    def test_duplicate_username(
        self, test_user: Any, pkcs12_data: bytes
    ) -> None:
        """Test form with existing username."""
        uploaded_file = SimpleUploadedFile(
            "test.p12", pkcs12_data, content_type="application/x-pkcs12"
        )
        form = RegisterForm(
            data={
                "username": "testuser",  # Already exists
                "pkcs12_password": "testpassword",
            },
            files={"pkcs12_file": uploaded_file},
        )

        assert form.is_valid() is False
        assert "username" in form.errors
