from __future__ import annotations

import unittest

from sqlalchemy import BigInteger, create_engine, func, select
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 import master_data  # noqa: E402
from app.models.base import Base  # noqa: E402
from app.models.operations import Process, WorkCenter  # noqa: E402
from app.models.org import Department  # noqa: E402


class MasterDataDefaultOperationFoundationTest(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_list_processes_seeds_default_process_for_empty_system(self) -> None:
        self.assertEqual(self.db.scalar(select(func.count(Process.id))), 0)

        rows = master_data.list_processes(limit=100, db=self.db)

        self.assertEqual(len(rows), 1)
        self.assertEqual(rows[0].process_code, "PROC-DEFAULT")
        self.assertEqual(rows[0].process_name, "系统默认工序")
        self.assertEqual(self.db.scalar(select(func.count(Process.id))), 1)

    def test_list_work_centers_seeds_default_work_center_for_empty_system(self) -> None:
        self.assertEqual(self.db.scalar(select(func.count(Department.id))), 0)
        self.assertEqual(self.db.scalar(select(func.count(WorkCenter.id))), 0)

        rows = master_data.list_work_centers(limit=100, db=self.db)

        self.assertEqual(len(rows), 1)
        self.assertEqual(rows[0].center_code, "WC-DEFAULT")
        self.assertEqual(rows[0].center_name, "系统默认工作中心")
        self.assertEqual(rows[0].dept_name, "总公司")
        self.assertEqual(self.db.scalar(select(func.count(Department.id))), 1)
        self.assertEqual(self.db.scalar(select(func.count(WorkCenter.id))), 1)
