"""Integration tests for IUCLID export API endpoint."""

import io
import zipfile
from uuid import uuid4

from django.test import TestCase, tag

from epdb.logic import PackageManager, UserManager
from epdb.models import Node, Pathway


@tag("iuclid")
class IUCLIDExportAPITest(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = UserManager.create_user(
            "iuclid-api-user",
            "iuclid-api@test.com",
            "TestPass123",
            set_setting=False,
            add_to_group=False,
            is_active=True,
        )
        default_pkg = cls.user.default_package
        cls.user.default_package = None
        cls.user.save()
        default_pkg.delete()

        cls.package = PackageManager.create_package(cls.user, "IUCLID API Test Package")

        cls.pathway = Pathway.create(
            cls.package,
            "c1ccccc1",
            name="Export Test Pathway",
        )
        Node.create(cls.pathway, "c1ccc(O)cc1", depth=1, name="Phenol")

        # Unauthorized user
        cls.other_user = UserManager.create_user(
            "iuclid-other-user",
            "other@test.com",
            "TestPass123",
            set_setting=False,
            add_to_group=False,
            is_active=True,
        )
        other_pkg = cls.other_user.default_package
        cls.other_user.default_package = None
        cls.other_user.save()
        other_pkg.delete()

    def test_export_returns_zip(self):
        self.client.force_login(self.user)
        url = f"/api/v1/pathway/{self.pathway.uuid}/export/iuclid"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Type"], "application/zip")
        self.assertIn(".i6z", response["Content-Disposition"])

        self.assertTrue(zipfile.is_zipfile(io.BytesIO(response.content)))

    def test_export_contains_expected_files(self):
        self.client.force_login(self.user)
        url = f"/api/v1/pathway/{self.pathway.uuid}/export/iuclid"
        response = self.client.get(url)

        with zipfile.ZipFile(io.BytesIO(response.content)) as zf:
            names = zf.namelist()
            self.assertIn("manifest.xml", names)
            i6d_files = [n for n in names if n.endswith(".i6d")]
            self.assertEqual(len(i6d_files), 4)

    def test_anonymous_returns_401(self):
        self.client.logout()
        url = f"/api/v1/pathway/{self.pathway.uuid}/export/iuclid"
        response = self.client.get(url)
        self.assertEqual(response.status_code, 401)

    def test_unauthorized_user_returns_403(self):
        self.client.force_login(self.other_user)
        url = f"/api/v1/pathway/{self.pathway.uuid}/export/iuclid"
        response = self.client.get(url)
        self.assertEqual(response.status_code, 403)

    def test_nonexistent_pathway_returns_404(self):
        self.client.force_login(self.user)
        url = f"/api/v1/pathway/{uuid4()}/export/iuclid"
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)
