import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any

from adafri.v1.base.firebase_collection import FirebaseCollectionBase

DISCUSSION_COLLECTION = 'workflow_discussion'

DISCUSSION_PICKABLE_FIELDS = [
    'id', 'workspaceId', 'authorUid', 'authorName',
    'content', 'type', 'createdAt',
]

DISCUSSION_TYPES = ['comment', 'status_change', 'approval']


def _now() -> str:
    return datetime.now(timezone.utc).isoformat()


def _new_id() -> str:
    return str(uuid.uuid4())


@dataclass(init=False)
class WorkflowDiscussionMessage(FirebaseCollectionBase):
    id: str
    workspaceId: str
    authorUid: str
    authorName: str
    content: str
    type: str
    createdAt: str

    def __init__(self, data=None, **kwargs):
        super().__init__(collection_name=DISCUSSION_COLLECTION, **kwargs)
        d = data or {}
        self.id = d.get('id') or _new_id()
        self.workspaceId = d.get('workspaceId', '')
        self.authorUid = d.get('authorUid', '')
        self.authorName = d.get('authorName', '')
        self.content = d.get('content', '')
        self.type = d.get('type', 'comment')
        self.createdAt = d.get('createdAt') or _now()

    @classmethod
    def from_dict(cls, obj: Any, **kwargs) -> 'WorkflowDiscussionMessage':
        return cls(obj, **kwargs)

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'workspaceId': self.workspaceId,
            'authorUid': self.authorUid,
            'authorName': self.authorName,
            'content': self.content,
            'type': self.type,
            'createdAt': self.createdAt,
        }

    @staticmethod
    def toListDict(items: list, fields=None) -> list:
        return [item.to_dict() for item in items]

    @classmethod
    def listByWorkspace(cls, workspace_id: str) -> 'list[WorkflowDiscussionMessage]':
        inst = cls()
        docs = (
            inst.collection()
            .where('workspaceId', '==', workspace_id)
            .order_by('createdAt')
            .stream()
        )
        return [cls({**d.to_dict(), 'id': d.id}) for d in docs]

    def save(self) -> 'WorkflowDiscussionMessage':
        self.collection().document(self.id).set(self.to_dict())
        return self
