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

from adafri.v1.base.firebase_collection import FirebaseCollectionBase

INVITE_COLLECTION = 'workflow_invites'

INVITE_PICKABLE_FIELDS = [
    'id', 'workspaceId', 'email', 'role', 'teamIds',
    'invitedBy', 'createdAt', 'status',
]

INVITE_MUTABLE_FIELDS = ['status', 'teamIds']

INVITE_STATUSES = ['pending', 'accepted', 'revoked']


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


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


@dataclass(init=False)
class WorkflowInvite(FirebaseCollectionBase):
    id: str
    workspaceId: str
    email: str
    role: str
    teamIds: list
    invitedBy: str
    createdAt: str
    status: str

    def __init__(self, data=None, **kwargs):
        super().__init__(collection_name=INVITE_COLLECTION, **kwargs)
        d = data or {}
        self.id = d.get('id') or _new_id()
        self.workspaceId = d.get('workspaceId', '')
        self.email = d.get('email', '')
        self.role = d.get('role', 'viewer')
        self.teamIds = list(d.get('teamIds') or [])
        self.invitedBy = d.get('invitedBy', '')
        self.createdAt = d.get('createdAt') or _now()
        self.status = d.get('status', 'pending')

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

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'workspaceId': self.workspaceId,
            'email': self.email,
            'role': self.role,
            'teamIds': self.teamIds,
            'invitedBy': self.invitedBy,
            'createdAt': self.createdAt,
            'status': self.status,
        }

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

    @classmethod
    def find(cls, invite_id: str) -> 'Optional[WorkflowInvite]':
        inst = cls()
        doc = inst.collection().document(invite_id).get()
        if not doc.exists:
            return None
        return cls({**doc.to_dict(), 'id': doc.id})

    @classmethod
    def findByEmail(cls, workspace_id: str, email: str) -> 'Optional[WorkflowInvite]':
        inst = cls()
        docs = (
            inst.collection()
            .where('workspaceId', '==', workspace_id)
            .where('email', '==', email)
            .where('status', '==', 'pending')
            .limit(1)
            .stream()
        )
        for d in docs:
            return cls({**d.to_dict(), 'id': d.id})
        return None

    @classmethod
    def findByWorkspace(cls, workspace_id: str) -> 'list[WorkflowInvite]':
        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) -> 'WorkflowInvite':
        self.collection().document(self.id).set(self.to_dict())
        return self

    def update(self, data: dict) -> 'WorkflowInvite':
        filtered = {k: v for k, v in data.items() if k in INVITE_MUTABLE_FIELDS}
        self.collection().document(self.id).update(filtered)
        for k, v in filtered.items():
            setattr(self, k, v)
        return self

    def delete(self) -> None:
        self.collection().document(self.id).delete()
