from datetime import date
from unittest.mock import patch

from django.test import TestCase

from basic_info import models as basic_models
from settlement.models import (
    DailySettlementConfig,
    NotificationChannelEnum,
    SettlementModuleEnum,
)
from settlement.tasks import run_daily_settlement


class SettlementTableMappingIntegrationTestCase(TestCase):
    def test_daily_settlement_config_can_persist_in_real_db(self):
        merchant = basic_models.Merchant.objects.create(
            name='表映射测试商户',
            type=basic_models.MerchantTypeEnum.FACTORY,
        )

        config = DailySettlementConfig.objects.create(
            merchant=merchant,
            settlement_modules=[SettlementModuleEnum.PLATE_ORDER],
            notification_enabled=False,
            notification_channel=NotificationChannelEnum.NONE,
        )

        fetched = DailySettlementConfig.objects.get(id=config.id)
        self.assertEqual(fetched.merchant_id, merchant.id)
        self.assertEqual(fetched.settlement_modules, [SettlementModuleEnum.PLATE_ORDER])

    @patch('settlement.tasks.run_merchant_daily_settlement.delay')
    @patch('settlement.tasks.timezone.localdate')
    def test_run_daily_settlement_queries_real_config_table(
        self,
        mock_localdate,
        mock_delay,
    ):
        mock_localdate.return_value = date(2026, 2, 9)

        merchant = basic_models.Merchant.objects.create(
            name='任务查询测试商户',
            type=basic_models.MerchantTypeEnum.FACTORY,
        )
        DailySettlementConfig.objects.create(
            merchant=merchant,
            settlement_modules=[SettlementModuleEnum.PLATE_ORDER],
            notification_enabled=False,
            notification_channel=NotificationChannelEnum.NONE,
        )

        result = run_daily_settlement.run()

        self.assertEqual(result['total_merchants'], 1)
        self.assertEqual(result['settlement_date'], '2026-02-08')
        mock_delay.assert_called_once_with(
            merchant_id=merchant.id,
            settlement_date='2026-02-08',
        )
