# -*- coding: utf-8 -*-
"""test_target_service.py — 目标管理测试"""

import pytest

from service_monitor.services import target_service as ts


def test_local_target_auto_created(tmp_data):
    targets = ts.list_targets("admin")
    assert any(t["id"] == "local" for t in targets)
    local = [t for t in targets if t["id"] == "local"][0]
    assert local["built_in"] is True


def test_create_remote_target(tmp_data):
    view = ts.create_target({
        "name": "生产DB", "host": "192.168.1.10", "port": 22,
        "username": "root", "password": "secret123",
    })
    assert view["type"] == "remote"
    assert view["has_password"] is True
    # 密码不明文返回
    assert "password" not in view
    assert "password_enc" not in view

    # 存储中是密文
    raw = ts.get_target(view["id"])
    assert raw["password_enc"].startswith("enc:")


def test_create_validation(tmp_data):
    with pytest.raises(ValueError):
        ts.create_target({"name": "", "host": "1.2.3.4", "username": "root", "password": "x"})
    with pytest.raises(ValueError):
        ts.create_target({"name": "x", "host": "bad host!", "username": "root", "password": "x"})
    with pytest.raises(ValueError):
        ts.create_target({"name": "x", "host": "1.2.3.4", "username": "root", "password": ""})


def test_normal_user_sees_only_local(tmp_data):
    ts.create_target({"name": "远程", "host": "1.2.3.4", "username": "root", "password": "x"})
    user_view = ts.list_targets("user")
    assert len(user_view) == 1
    assert user_view[0]["type"] == "local"
    admin_view = ts.list_targets("admin")
    assert len(admin_view) == 2


def test_delete_target(tmp_data):
    view = ts.create_target({"name": "临时", "host": "1.2.3.4", "username": "root", "password": "x"})
    assert ts.delete_target(view["id"]) is True
    assert ts.get_target(view["id"]) is None


def test_cannot_delete_local(tmp_data):
    with pytest.raises(ValueError):
        ts.delete_target("local")


def test_update_target(tmp_data):
    view = ts.create_target({"name": "旧名", "host": "1.2.3.4", "username": "root", "password": "x"})
    updated = ts.update_target(view["id"], {"name": "新名"})
    assert updated["name"] == "新名"


def test_make_executor_local(tmp_data):
    from service_monitor.utils.executor import LocalExecutor
    local = ts.get_target("local")
    exe = ts.make_executor(local, "run1")
    assert isinstance(exe, LocalExecutor)
