import pytest
from fastapi import HTTPException

from api.v1.modules.crm.activities import service
from api.v1.modules.crm.activities.dto import ActivityCreate

T, C = 1, 1


def test_create_rejects_invalid_type(db):
    with pytest.raises(HTTPException) as exc:
        service.create_activity(db, ActivityCreate(activity_type="invalido", subject="x"), T, C)
    assert exc.value.status_code == 422


def test_complete_activity_sets_timestamp(db):
    activity = service.create_activity(db, ActivityCreate(activity_type="call", subject="Llamar al cliente"), T, C)
    assert activity.status == "pending"
    done = service.complete_activity(db, activity.id, T, C)
    assert done.status == "completed"
    assert done.completed_at is not None


def test_create_rejects_unknown_related_entity(db):
    with pytest.raises(HTTPException) as exc:
        service.create_activity(
            db, ActivityCreate(activity_type="task", subject="x", opportunity_id=999), T, C
        )
    assert exc.value.status_code == 422


def test_filter_by_type_and_status(db):
    service.create_activity(db, ActivityCreate(activity_type="call", subject="a"), T, C)
    service.create_activity(db, ActivityCreate(activity_type="meeting", subject="b"), T, C)
    calls = service.get_activities(db, T, C, activity_type="call")
    assert len(calls) == 1 and calls[0].activity_type == "call"
    pending = service.get_activities(db, T, C, activity_status="pending")
    assert len(pending) == 2
