from unittest.mock import patch

from django.test import TestCase

from basic_info import models as basic_models
from printing import models as printing_models


class TencentTiiaPlateOrderUploadTestCase(TestCase):
    def setUp(self):
        self.merchant = basic_models.Merchant.objects.create(
            name='测试商户',
            type=basic_models.MerchantTypeEnum.FACTORY,
        )
        # PlateOrder.customer 必填
        self.customer = basic_models.Customer.objects.create(
            merchant=self.merchant,
            name='客户A',
            mobile='13900000000',
            area='A',
        )

    @patch('api_v1.utils.tencentcloud_tiia.upload_image_url_to_tencent_tiia')
    def test_upload_plate_order_images_to_tencent_tiia_uploads_all_urls(self, mocked_upload):
        mocked_upload.side_effect = lambda **kwargs: {'mocked': True, 'kwargs': kwargs}

        po = printing_models.PlateOrder.objects.create(
            merchant=self.merchant,
            customer=self.customer,
            plate_image=[
                {'url': 'https://example.com/a.png'},
                {'path': 'uploads/2026/01/16/b.png'},  # 将由 build_public_media_url 归一化
                'https://example.com/c.png',
                {'imageUrl': 'https://example.com/d.png'},
            ],
        )

        from api_v1.utils.tencentcloud_tiia import upload_plate_order_images_to_tencent_tiia

        results = upload_plate_order_images_to_tencent_tiia(plate_order_id=po.id)

        # 至少应尝试上传 3 张绝对 URL（example.com: a/c/d）
        # uploads/... 会被转为基于 settings.QINIU_BUCKET_DOMAIN 的绝对/相对形式，这里不强耦合其结果，
        # 只要 uploader 被调用次数 >= 3 即可。
        self.assertGreaterEqual(mocked_upload.call_count, 3)

        # entity_id 必须为 plate_order_id
        for call in mocked_upload.call_args_list:
            self.assertEqual(call.kwargs.get('entity_id'), str(po.id))

        # 返回结构必须包含 ok/image_url 字段
        self.assertIsInstance(results, list)
        self.assertTrue(all(('ok' in r and 'image_url' in r) for r in results))

