from __future__ import annotations

import unittest

from sqlalchemy import BigInteger, create_engine
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import Session, sessionmaker


@compiles(BigInteger, "sqlite")
def _compile_bigint_for_sqlite(type_, compiler, **kw) -> str:
    _ = type_, compiler, kw
    return "INTEGER"


import app.models.master_data  # noqa: E402,F401
import app.models.miniapp  # noqa: E402,F401
import app.models.operations  # noqa: E402,F401
import app.models.org  # noqa: E402,F401
import app.models.planning  # noqa: E402,F401
import app.models.sales  # noqa: E402,F401
from app.models.base import Base  # noqa: E402
from app.services.system_config import (  # noqa: E402
    get_smart_operation_report_enabled,
    normalize_enabled_config_value,
    upsert_smart_operation_report_config,
)


class SmartOperationReportConfigTest(unittest.TestCase):
    def setUp(self) -> None:
        engine = create_engine("sqlite+pysqlite:///:memory:", future=True)
        Base.metadata.create_all(engine)
        self.SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
        self.db: Session = self.SessionLocal()

    def tearDown(self) -> None:
        self.db.close()

    def test_defaults_enabled(self) -> None:
        self.assertTrue(get_smart_operation_report_enabled(self.db))

    def test_normalizes_chinese_values(self) -> None:
        self.assertEqual(normalize_enabled_config_value("开启"), "开启")
        self.assertEqual(normalize_enabled_config_value("关闭"), "关闭")
        self.assertEqual(normalize_enabled_config_value(True), "开启")
        self.assertEqual(normalize_enabled_config_value(False), "关闭")

    def test_upsert_changes_enabled_state(self) -> None:
        upsert_smart_operation_report_config(self.db, enabled=False, updated_by=1, remark="未购买小程序")
        self.db.commit()
        self.assertFalse(get_smart_operation_report_enabled(self.db))


if __name__ == "__main__":
    unittest.main()
