"""MDYPlateOrderStaging 查询 API 测试"""

from datetime import timedelta

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.utils import timezone
from rest_framework.test import APIClient

from api_v1.models import MDYPlateOrderStaging


User = get_user_model()


class MDYPlateOrderStagingAPITestCase(TestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = User.objects.create_user(
            username="testuser",
            password="testpass123",
            email="test@example.com",
        )
        self.client.force_authenticate(user=self.user)

        view_perm = Permission.objects.get(codename="view_mdyplateorderstaging")
        self.user.user_permissions.add(view_perm)

        now = timezone.now()

        # older
        self.row1 = MDYPlateOrderStaging.objects.create(
            mdy_rowid="row1",
            ctime=now - timedelta(days=1),
            utime=now - timedelta(days=1, minutes=1),
            raw={
                "rowid": "row1",
                "ctime": "2025-01-01 00:00:00",
                "utime": "2025-01-01 00:01:00",
                "62d52f4b8d2972284492dd0e": "A001",  # 设计编号
                "62d52f4b8d2972284492dd2c": "款号A",  # 款号名称
            },
            related=[
                {
                    "rowid": "rel1",
                    "source": "drawing",
                    "source_name": "画图",
                    "设计师名字": "张三",
                }
            ],
        )

        # newer
        self.row2 = MDYPlateOrderStaging.objects.create(
            mdy_rowid="row2",
            ctime=now,
            utime=now,
            raw={
                "rowid": "row2",
                "ctime": "2025-01-02 00:00:00",
                "utime": "2025-01-02 00:01:00",
                "62d52f4b8d2972284492dd0e": "A002",  # 设计编号
                "62d52f4b8d2972284492dd2c": "款号B",  # 款号名称
            },
            related=[],
        )

    def test_list_default_order_and_flatten(self):
        resp = self.client.get("/api/v1/mdy-plate-order-staging/?limit=10&offset=0")
        self.assertEqual(resp.status_code, 200)

        payload = resp.json()
        self.assertEqual(payload["count"], 2)

        first = payload["results"][0]
        self.assertEqual(first["mdy_rowid"], "row2")  # -ctime 排序

        # raw 已按字段定义“可读化”
        self.assertIn("raw", first)
        self.assertIn("设计编号", first["raw"])
        self.assertEqual(first["raw"]["设计编号"], "A002")
        self.assertEqual(first["raw"]["款号名称"], "款号B")

        # related 以 list[dict] 返回
        self.assertIn("related", first)
        self.assertEqual(first["related"], [])

    def test_filter_by_design_no(self):
        resp = self.client.get(
            "/api/v1/mdy-plate-order-staging/?limit=10&offset=0&design_no=A001"
        )
        self.assertEqual(resp.status_code, 200)

        payload = resp.json()
        self.assertEqual(payload["count"], 1)
        self.assertEqual(payload["results"][0]["mdy_rowid"], "row1")

        self.assertEqual(payload["results"][0]["raw"]["设计编号"], "A001")
        self.assertEqual(payload["results"][0]["related"][0]["source"], "drawing")

    def test_filter_by_style_name_icontains(self):
        # 支持 <internal_field>__icontains=...（不暴露 raw__ 前缀）
        resp = self.client.get(
            "/api/v1/mdy-plate-order-staging/?limit=10&offset=0&style_name__icontains=款号"
        )
        self.assertEqual(resp.status_code, 200)
        payload = resp.json()
        self.assertEqual(payload["count"], 2)

    def test_filter_by_related_source(self):
        # related_source 是对外参数（隐藏 related__contains 实现）
        resp = self.client.get(
            "/api/v1/mdy-plate-order-staging/?limit=10&offset=0&related_source=drawing"
        )
        self.assertEqual(resp.status_code, 200)
        payload = resp.json()
        self.assertEqual(payload["count"], 1)
        self.assertEqual(payload["results"][0]["mdy_rowid"], "row1")

    def test_rejects_raw_prefix_params(self):
        # 对外 API 禁止直接使用 raw__/related__ 前缀
        resp = self.client.get(
            "/api/v1/mdy-plate-order-staging/?limit=10&offset=0&raw__design_no=A001"
        )
        self.assertEqual(resp.status_code, 400)
