from __future__ import annotations

import unittest

from pydantic import ValidationError
from sqlalchemy import create_engine, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, sessionmaker


import app.models.document_archive  # noqa: E402,F401
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.models.document_archive import DocumentArchive  # noqa: E402
from app.schemas.document_archives import DocumentArchiveBatchDownloadRequest  # noqa: E402


class DocumentArchiveModelTest(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 _archive(self, *, business_id: int = 1001, archive_version: int = 1) -> DocumentArchive:
        return DocumentArchive(
            document_type="销售订单",
            business_id=business_id,
            document_no="SO-20260611-0001",
            archive_version=archive_version,
            template_version="单据纸面V1",
            file_format="PDF",
            file_name="SO-20260611-0001.pdf",
            file_path="/archives/sales/SO-20260611-0001.pdf",
            file_hash="abc123",
            status="已归档",
            error_message=None,
            created_by=1,
        )

    def test_document_archive_round_trips_chinese_business_values(self) -> None:
        archive = self._archive()
        self.db.add(archive)
        self.db.commit()

        saved = self.db.execute(select(DocumentArchive).where(DocumentArchive.id == archive.id)).scalar_one()

        self.assertIsNotNone(saved.id)
        self.assertEqual(saved.status, "已归档")
        self.assertEqual(saved.template_version, "单据纸面V1")
        self.assertEqual(saved.archive_version, 1)

    def test_document_archive_rejects_duplicate_archive_version_format(self) -> None:
        self.db.add(self._archive())
        self.db.commit()

        self.db.add(self._archive())

        with self.assertRaises(IntegrityError):
            self.db.commit()

    def test_batch_download_request_requires_business_ids_when_omitted(self) -> None:
        with self.assertRaises(ValidationError):
            DocumentArchiveBatchDownloadRequest(document_type="销售订单")


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