"""IT-EXEC-001 / IT-SCR-001 — script CRUD and execution list."""

from __future__ import annotations

import pytest

from server.api.dependencies import get_script_service
from server.api.schemas import ScriptCreate
from server.api.scripts import create_script, list_executions, list_scripts
from server.domain.models import Script

pytestmark = pytest.mark.integration


async def _script_service(db_session, mock_request):
    mock_request.state.db = db_session
    return await get_script_service(mock_request)


@pytest.mark.asyncio
async def test_list_executions_empty(db_session, test_admin, mock_request):
    service = await _script_service(db_session, mock_request)
    body = await list_executions(
        limit=10,
        offset=0,
        status=None,
        script_id=None,
        admin=test_admin["admin"],
        service=service,
    )
    assert "items" in body
    assert "total" in body


@pytest.mark.asyncio
async def test_script_crud_minimal(db_session, test_admin, mock_request):
    service = await _script_service(db_session, mock_request)
    payload = ScriptCreate(name="it-test-script", content="echo ok", category="ops")

    created = await create_script(
        payload,
        mock_request,
        test_admin["admin"],
        service,
        db_session,
    )
    assert created["name"] == "it-test-script"
    assert created["id"] > 0

    scripts = await list_scripts(
        category=None,
        admin=test_admin["admin"],
        service=service,
    )
    names = [s["name"] for s in scripts]
    assert "it-test-script" in names

    row = await db_session.get(Script, created["id"])
    assert row is not None
