"""
补充 Process 列表接口的 node_count 字段覆盖

ProcessViewSet.list() 会对 queryset annotate(node_count)，对应 ProcessListSerializer 的只读字段。
"""

from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient

from stateflow import models

User = get_user_model()


class ProcessListNodeCountAPITestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(username="testuser", password="testpass")
        self.client.force_authenticate(user=self.user)

        self.state1 = models.State.objects.create(name="状态1")
        self.state2 = models.State.objects.create(name="状态2")

    def test_process_list_contains_node_count(self):
        process = models.Process.objects.create(name="带节点计数的流程")
        models.ProcessNode.objects.create(process=process, state=self.state1, order=0)
        models.ProcessNode.objects.create(process=process, state=self.state2, order=1)

        resp = self.client.get("/api/v1/stateflow/processes/?limit=10&offset=0")
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertEqual(resp.data["count"], 1)

        item = resp.data["results"][0]
        self.assertIn("node_count", item)
        self.assertEqual(item["node_count"], 2)


class ProcessNodesAPITestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(username="nodeuser", password="testpass")
        self.client.force_authenticate(user=self.user)

        self.state1 = models.State.objects.create(name="节点1", description="第一个节点")
        self.state2 = models.State.objects.create(name="节点2", description="第二个节点")
        self.process = models.Process.objects.create(name="节点查询流程")
        models.ProcessNode.objects.create(process=self.process, state=self.state1, order=0)
        models.ProcessNode.objects.create(process=self.process, state=self.state2, order=1)

    def test_process_nodes_endpoint_returns_ordered_states(self):
        url = f"/api/v1/stateflow/processes/{self.process.id}/nodes/"
        resp = self.client.get(url)
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertEqual(resp.data["process_id"], self.process.id)
        self.assertEqual(resp.data["count"], 2)
        node_ids = [node["id"] for node in resp.data["nodes"]]
        self.assertEqual(node_ids, [self.state1.id, self.state2.id])
        self.assertEqual(resp.data["nodes"][0]["name"], self.state1.name)
        self.assertEqual(resp.data["nodes"][1]["name"], self.state2.name)

    def test_process_nodes_endpoint_404_when_missing(self):
        resp = self.client.get("/api/v1/stateflow/processes/9999/nodes/")
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)


