"""Jira router API tests (FASE-1.3)."""

import uuid

from app.models.audit import AuditLog
from app.models.jira_link import JiraLink, JiraLinkEntityType


def test_create_link_rejects_invalid_issue_key(client, admin_user, auth_headers):
    response = client.post(
        "/api/v1/jira/links",
        json={
            "entity_type": "test",
            "entity_id": str(uuid.uuid4()),
            "jira_issue_key": "invalid-key",
        },
        headers=auth_headers,
    )
    # Pydantic validation (422) or global validation handler (400)
    assert response.status_code in (400, 422)


def test_create_link_returns_201(client, admin_user, auth_headers, db):
    entity_id = uuid.uuid4()
    response = client.post(
        "/api/v1/jira/links",
        json={
            "entity_type": "test",
            "entity_id": str(entity_id),
            "jira_issue_key": "SEC-1234",
        },
        headers=auth_headers,
    )
    assert response.status_code == 201
    data = response.json()
    assert data["jira_issue_key"] == "SEC-1234"
    assert data["entity_id"] == str(entity_id)

    audit = (
        db.query(AuditLog)
        .filter(AuditLog.action == "JIRA_LINK_CREATED")
        .order_by(AuditLog.timestamp.desc())
        .first()
    )
    assert audit is not None
    assert audit.details.get("jira_issue_key") == "SEC-1234"


def test_list_links_filters_by_entity(client, admin_user, auth_headers, db):
    entity_id = uuid.uuid4()
    link = JiraLink(
        entity_type=JiraLinkEntityType.test,
        entity_id=entity_id,
        jira_issue_key="SEC-555",
        created_by=admin_user.id,
    )
    db.add(link)
    db.commit()

    response = client.get(
        "/api/v1/jira/links",
        params={"entity_type": "test", "entity_id": str(entity_id)},
        headers=auth_headers,
    )
    assert response.status_code == 200
    rows = response.json()
    assert len(rows) == 1
    assert rows[0]["jira_issue_key"] == "SEC-555"
