from __future__ import annotations

import unittest
from datetime import UTC, date, datetime

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.api.routes.sales import build_sales_order_no  # noqa: E402
from app.models.base import Base  # noqa: E402
from app.models.sales import Customer, SalesOrder  # noqa: E402


class SalesOrderNoGenerationTest(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()
        self.customer = Customer(
            id=1,
            customer_code="CUS-001",
            customer_name="测试客户",
            short_name="客户",
            status="ACTIVE",
        )
        self.db.add(self.customer)
        self.db.commit()

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

    def _add_sales_order(self, order_no: str) -> None:
        now = datetime.now(UTC)
        self.db.add(
            SalesOrder(
                order_no=order_no,
                customer_id=self.customer.id,
                order_date=date.today(),
                promised_date=None,
                sales_employee_id=None,
                delivery_address=None,
                tax_rate=0,
                total_amount=0,
                status="OPEN",
                created_at=now,
                updated_at=now,
            )
        )
        self.db.commit()

    def test_sales_order_no_starts_from_year_five_digit_sequence(self) -> None:
        year = date.today().strftime("%Y")

        self.assertEqual(build_sales_order_no(self.db, self.customer), f"销售{year}-00001")

    def test_sales_order_no_increments_only_matching_current_year_orders(self) -> None:
        year = date.today().strftime("%Y")
        previous_year = str(int(year) - 1)
        self._add_sales_order(f"销售{year}-00001")
        self._add_sales_order(f"销售{year}-00009")
        self._add_sales_order(f"{previous_year}-00099")
        self._add_sales_order(f"{year}-00099")
        self._add_sales_order("SO-NB-20260523-CUS001-001")

        self.assertEqual(build_sales_order_no(self.db, self.customer), f"销售{year}-00010")

    def test_sales_order_no_ignores_malformed_same_year_codes(self) -> None:
        year = date.today().strftime("%Y")
        self._add_sales_order(f"销售{year}-001")
        self._add_sales_order(f"销售{year}-000001")
        self._add_sales_order(f"销售{year}-ABCDE")

        self.assertEqual(build_sales_order_no(self.db, self.customer), f"销售{year}-00001")


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