"""Tests for CHECK_FILE replace preserving origin file_path on disk."""
import os
import tempfile
import unittest
from unittest.mock import MagicMock

from app.services.document_service import DocumentService


def _file_row(file_id: str, file_path: str, image_path: str = "", thumbnail_path: str = ""):
    return (
        file_id,
        "name.pdf",
        "name.pdf",
        "pdf",
        file_path,
        "pdf",
        "name.pdf",
        "2025-01-01T00:00:00",
        100,
        "",
        "",
        image_path,
        thumbnail_path,
        "agent1",
    )


class TestPreserveSourceOnReplace(unittest.TestCase):
    def _minimal_service(self, mock_db: MagicMock) -> DocumentService:
        svc = DocumentService.__new__(DocumentService)
        svc.db_service = mock_db
        svc.vector_db = None
        svc.bm25_index = None
        return svc

    def test_delete_document_preserves_origin_when_flag_set(self):
        with tempfile.TemporaryDirectory() as tmp:
            origin = os.path.join(tmp, "origin.pdf")
            preview = os.path.join(tmp, "preview.png")
            with open(origin, "wb") as f:
                f.write(b"pdf-bytes")
            with open(preview, "wb") as f:
                f.write(b"png-bytes")

            file_id = "dup-old"
            mock_db = MagicMock()
            mock_db.get_file.return_value = _file_row(file_id, origin, image_path=preview)
            mock_db.get_extracted_images.return_value = []
            mock_db.delete_file.return_value = True

            svc = self._minimal_service(mock_db)
            ok = svc.delete_document(file_id, preserve_source_path=True)

            self.assertTrue(ok)
            self.assertTrue(os.path.isfile(origin), "origin PDF must remain on disk")
            self.assertFalse(os.path.isfile(preview), "generated preview should be removed")

    def test_replace_existing_file_does_not_delete_origin(self):
        with tempfile.TemporaryDirectory() as tmp:
            origin = os.path.join(tmp, "01776717057_report.pdf")
            with open(origin, "wb") as f:
                f.write(b"pdf")

            file_id = "old-id"
            mock_db = MagicMock()
            mock_db.get_file.return_value = _file_row(file_id, origin)
            mock_db.get_extracted_images.return_value = []
            mock_db.delete_file.return_value = True

            svc = self._minimal_service(mock_db)
            ok = svc._replace_existing_file(file_id)

            self.assertTrue(ok)
            self.assertTrue(os.path.isfile(origin))
            mock_db.delete_file.assert_called_once_with(file_id)


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