"""Tests for Jira link model and jira_service link helpers (FASE-1.1).

Verifies persistence with SQLite test DB and link creation when Jira is disabled.
API routes are covered indirectly via jira_service (same code path as the router).
"""

import uuid

import pytest
from pydantic import ValidationError

from app.models.jira_link import JiraLink, JiraLinkEntityType, JiraSyncDirection
from app.schemas.jira_schema import JiraLinkCreate
from app.services import jira_service


def test_jira_link_persist_and_query(db, admin_user):
    entity_id = uuid.uuid4()
    link = JiraLink(
        entity_type=JiraLinkEntityType.test,
        entity_id=entity_id,
        jira_issue_key="PROJ-42",
        jira_issue_id="10001",
        sync_direction=JiraSyncDirection.bidirectional,
        created_by=admin_user.id,
        sync_metadata={"foo": "bar"},
    )
    db.add(link)
    db.commit()
    db.refresh(link)

    loaded = db.query(JiraLink).filter(JiraLink.id == link.id).one()
    assert loaded.entity_type == JiraLinkEntityType.test
    assert loaded.entity_id == entity_id
    assert loaded.jira_issue_key == "PROJ-42"
    assert loaded.sync_metadata == {"foo": "bar"}
    assert loaded.created_by == admin_user.id


def test_jira_link_create_schema_accepts_valid_issue_key():
    body = JiraLinkCreate(
        entity_type=JiraLinkEntityType.campaign,
        entity_id=uuid.uuid4(),
        jira_issue_key="ABC-1",
    )
    assert body.jira_issue_key == "ABC-1"
    assert body.sync_direction == JiraSyncDirection.bidirectional


def test_jira_link_create_schema_rejects_invalid_issue_key():
    with pytest.raises(ValidationError):
        JiraLinkCreate(
            entity_type=JiraLinkEntityType.test,
            entity_id=uuid.uuid4(),
            jira_issue_key="proj-123",
        )


def test_create_link_via_service_persists(db, admin_user):
    eid = uuid.uuid4()
    link = jira_service.create_link(
        db,
        entity_type=JiraLinkEntityType.test,
        entity_id=eid,
        jira_issue_key="TST-99",
        sync_direction=JiraSyncDirection.bidirectional,
        created_by=admin_user.id,
    )
    db.commit()
    db.refresh(link)
    assert link.jira_issue_key == "TST-99"
    assert link.entity_id == eid


def test_list_links_filters_by_entity(db, admin_user):
    eid = uuid.uuid4()
    jira_service.create_link(
        db,
        entity_type=JiraLinkEntityType.technique,
        entity_id=eid,
        jira_issue_key="TECH-7",
        sync_direction=JiraSyncDirection.jira_to_aegis,
        created_by=admin_user.id,
    )
    db.commit()
    rows = jira_service.list_links(
        db,
        entity_type=JiraLinkEntityType.technique,
        entity_id=eid,
    )
    assert len(rows) == 1
    assert rows[0].jira_issue_key == "TECH-7"
    assert rows[0].sync_direction == JiraSyncDirection.jira_to_aegis
