"""IT-SCH-001 — schedule CRUD with audit."""

from __future__ import annotations

from datetime import datetime, timezone

import pytest

from server.api.schemas import ScheduleCreate, ScheduleUpdate
from server.api.settings import create_schedule, delete_schedule, list_schedules, update_schedule

pytestmark = pytest.mark.integration


@pytest.mark.asyncio
async def test_schedule_create_once_push_parses_fire_at(db_session, test_admin, test_server, mock_request):
    """once 模式 fire_at 须写入 ORM datetime（非 ISO 字符串），避免 500。"""
    fire = datetime.now(timezone.utc).replace(microsecond=0)
    payload = ScheduleCreate(
        name="it-schedule-once",
        server_ids=f"[{test_server.id}]",
        run_mode="once",
        cron_expr="30 14 * * *",
        fire_at=fire.isoformat(),
        schedule_type="push",
        source_path="/tmp/nexus-schedule-src",
    )
    assert isinstance(payload.fire_at, datetime)

    created = await create_schedule(payload, mock_request, test_admin["admin"], db_session)
    assert created["id"] > 0
    assert created["fire_at"] is not None

    await delete_schedule(created["id"], mock_request, test_admin["admin"], db_session)


@pytest.mark.asyncio
async def test_schedule_crud_minimal(db_session, test_admin, test_server, mock_request):
    payload = ScheduleCreate(
        name="it-schedule-test",
        server_ids=f"[{test_server.id}]",
        run_mode="cron",
        cron_expr="0 3 * * *",
        schedule_type="push",
        source_path="/tmp/nexus-schedule-src",
        target_path="/www/wwwroot",
    )

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

    rows = await list_schedules(test_admin["admin"], db_session)
    assert any(r["id"] == created["id"] for r in rows)

    updated = await update_schedule(
        created["id"],
        ScheduleUpdate(name="it-schedule-renamed"),
        mock_request,
        test_admin["admin"],
        db_session,
    )
    assert updated["name"] == "it-schedule-renamed"

    await delete_schedule(created["id"], mock_request, test_admin["admin"], db_session)
    rows_after = await list_schedules(test_admin["admin"], db_session)
    assert not any(r["id"] == created["id"] for r in rows_after)
