"""
KPI字典模块测试
"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from tests.conftest import create_test_user, get_token_for_user, auth_header, create_test_kpi


class TestKPIs:
    """KPI字典CRUD测试"""

    def test_list_kpis_empty(self, client: TestClient, db: Session):
        """空列表"""
        create_test_user(db)
        token = get_token_for_user(client)

        resp = client.get("/api/cma/kpis", headers=auth_header(token))
        assert resp.status_code == 200
        assert resp.json()["data"] == []

    def test_create_kpi(self, client: TestClient, db: Session):
        """创建KPI"""
        create_test_user(db)
        token = get_token_for_user(client)

        resp = client.post(
            "/api/cma/kpis",
            headers=auth_header(token),
            json={
                "kpi_code": "F_REVENUE_002",
                "kpi_name": "测试收入指标",
                "dimension": "finance",
                "target_value": 1000000,
                "unit": "元",
                "formula": "测试公式",
                "data_source": "测试系统",
                "data_owner": "测试管理员",
            },
        )
        assert resp.status_code == 200
        assert resp.json()["kpi_code"] == "F_REVENUE_002"

    def test_create_kpi_duplicate_code(self, client: TestClient, db: Session):
        """重复KPI编码被拒绝"""
        create_test_user(db)
        token = get_token_for_user(client)

        # 先创建一个
        client.post(
            "/api/cma/kpis",
            headers=auth_header(token),
            json={
                "kpi_code": "F_REVENUE_003",
                "kpi_name": "收入指标",
                "dimension": "finance",
                "target_value": 500000,
                "unit": "%",
                "formula": "测试公式",
                "data_source": "测试系统",
                "data_owner": "测试管理员",
            },
        )

        # 重复创建
        resp = client.post(
            "/api/cma/kpis",
            headers=auth_header(token),
            json={
                "kpi_code": "F_REVENUE_003",
                "kpi_name": "重复编码",
                "dimension": "finance",
                "target_value": 500000,
                "unit": "%",
                "formula": "测试公式",
                "data_source": "测试系统",
                "data_owner": "测试管理员",
            },
        )
        assert resp.status_code == 400

    def test_update_kpi(self, client: TestClient, db: Session):
        """编辑KPI"""
        create_test_user(db)
        token = get_token_for_user(client)
        kpi = create_test_kpi(db, kpi_code="F_TEST_001")

        resp = client.put(
            f"/api/cma/kpis/{kpi.id}",
            headers=auth_header(token),
            json={"kpi_name": "已编辑指标", "target_value": 200},
        )
        assert resp.status_code == 200
        assert resp.json()["kpi_name"] == "已编辑指标"
        assert resp.json()["target_value"] == 200

    def test_delete_kpi(self, client: TestClient, db: Session):
        """删除KPI（软删除）"""
        create_test_user(db)
        token = get_token_for_user(client)
        kpi = create_test_kpi(db, kpi_code="F_DEL_001")

        resp = client.delete(
            f"/api/cma/kpis/{kpi.id}",
            headers=auth_header(token),
        )
        assert resp.status_code == 200

        # 验证已被软删除（status变为非active）
        get_resp = client.get(
            f"/api/cma/kpis/{kpi.id}",
            headers=auth_header(token),
        )
        assert get_resp.status_code == 200
        assert get_resp.json()["status"] != "active"

    def test_get_kpi_by_code(self, client: TestClient, db: Session):
        """按编码查询KPI（通过列表过滤）"""
        create_test_user(db)
        token = get_token_for_user(client)
        create_test_kpi(db, kpi_code="F_CODE_001", kpi_name="编码查询测试")

        # 通过列表+参数过滤
        resp = client.get(
            "/api/cma/kpis?code=F_CODE_001",
            headers=auth_header(token),
        )
        assert resp.status_code == 200
        data = resp.json()["data"]
        assert len(data) >= 1
        assert data[0]["kpi_name"] == "编码查询测试"
