"""GraphQL types, queries, and mutations for analytics app."""

import strawberry
from strawberry import ID
from strawberry.types import Info

from accounts.models import WorkspaceMembership

from .models import Event


@strawberry.type
class EventType:
    """GraphQL type for Event model."""

    id: ID
    name: str
    occurred_at: str
    properties: strawberry.scalars.JSON
    created_at: str
    updated_at: str
    workspace_id: ID
    member_id: ID | None

    @classmethod
    def from_model(cls, event: Event) -> "EventType":
        return cls(
            id=ID(str(event.pk)),
            name=event.name,
            occurred_at=event.occurred_at.isoformat() if event.occurred_at else "",
            properties=event.properties or {},
            created_at=event.created_at.isoformat() if event.created_at else "",
            updated_at=event.updated_at.isoformat() if event.updated_at else "",
            workspace_id=ID(str(event.workspace_id)),
            member_id=ID(str(event.member_id)) if event.member_id else None,
        )


@strawberry.type
class AnalyticsQuery:
    """Queries for analytics app."""

    @strawberry.field
    def events(
        self,
        info: Info,
        workspace_id: ID,
        name: str | None = None,
        member_id: ID | None = None,
        limit: int = 100,
    ) -> list[EventType]:
        """Get events in a workspace."""
        user = info.context.user
        if not user or not user.is_authenticated:
            return []

        has_access = WorkspaceMembership.objects.filter(user=user, workspace_id=workspace_id).exists()
        if not has_access:
            return []

        events = Event.objects.filter(workspace_id=workspace_id)

        if name:
            events = events.filter(name=name)
        if member_id:
            events = events.filter(member_id=member_id)

        return [EventType.from_model(e) for e in events.order_by("-occurred_at")[:limit]]

    @strawberry.field
    def event(self, info: Info, id: ID) -> EventType | None:
        """Get a specific event by ID."""
        user = info.context.user
        if not user or not user.is_authenticated:
            return None

        try:
            event = Event.objects.get(pk=id)
        except Event.DoesNotExist:
            return None

        has_access = WorkspaceMembership.objects.filter(user=user, workspace=event.workspace).exists()
        if not has_access:
            return None

        return EventType.from_model(event)
