"""Tests for validation logic with tmp_path fixtures."""

from pathlib import Path

from loony.validate import validate_service

VALID_SCHEMA = (
    "tables:\n  raw_test:\n    description: test\n"
    "    sync_mode: replace\n    primary_key: [id]\n"
    "    columns:\n      id: { type: integer, description: ID }"
)


class TestValidateService:
    def _make_project(
        self, tmp_path: Path, loony_yaml: str = "", schema_yaml: str = "", scripts: dict | None = None,
    ) -> Path:
        """Helper to create a minimal project structure."""
        (tmp_path / "loony.yaml").write_text(loony_yaml or "name: test-svc")
        (tmp_path / "schema.yaml").write_text(schema_yaml or VALID_SCHEMA)
        (tmp_path / "scripts").mkdir(exist_ok=True)
        (tmp_path / "transforms").mkdir(exist_ok=True)
        if scripts:
            for name, content in scripts.items():
                (tmp_path / "scripts" / name).write_text(content)
        return tmp_path

    def test_valid_empty_project(self, tmp_path: Path) -> None:
        project = self._make_project(tmp_path)
        result = validate_service(project)
        assert result.passed

    def test_missing_loony_yaml(self, tmp_path: Path) -> None:
        (tmp_path / "schema.yaml").write_text(VALID_SCHEMA)
        result = validate_service(tmp_path)
        assert not result.passed

    def test_missing_schema_yaml(self, tmp_path: Path) -> None:
        (tmp_path / "loony.yaml").write_text("name: test")
        result = validate_service(tmp_path)
        assert not result.passed

    def test_script_with_run_function(self, tmp_path: Path) -> None:
        project = self._make_project(tmp_path, scripts={
            "my_source.py": "def run(conn):\n    return {'rows': 0}\n",
        })
        result = validate_service(project)
        assert result.passed

    def test_script_missing_run_function(self, tmp_path: Path) -> None:
        project = self._make_project(tmp_path, scripts={
            "bad_script.py": "def process():\n    pass\n",
        })
        result = validate_service(project)
        # Should have a failing check about run()
        failed = [c for c in result.checks if not c.ok]
        assert len(failed) >= 1

    def test_schema_with_valid_table(self, tmp_path: Path) -> None:
        project = self._make_project(tmp_path, schema_yaml="""\
tables:
  raw_users:
    description: "User data"
    sync_mode: merge
    primary_key: [id]
    columns:
      id: { type: integer, description: "User ID" }
""")
        result = validate_service(project)
        assert result.passed
