# core/auth.py
from __future__ import annotations

import structlog

from core.protocol import AuthFlow
from core.store import StateStore

logger = structlog.get_logger(__name__)


def _to_dict(flow: AuthFlow) -> dict:
    return {
        "user_id": flow.user_id,
        "platform": flow.platform,
        "state": flow.state,
        "platform_user_id": flow.platform_user_id,
    }


def _from_dict(d: dict) -> AuthFlow:
    return AuthFlow(
        user_id=d["user_id"],
        platform=d["platform"],
        state=d["state"],
        platform_user_id=d.get("platform_user_id"),
    )


class AuthManager:
    def __init__(self, platform: object, store: StateStore) -> None:
        self._store = store

    async def start_flow(self, user_id: str, platform: str) -> AuthFlow:
        flow = AuthFlow(user_id=user_id, platform=platform, state="pending")
        await self._store.set(f"auth:{user_id}", _to_dict(flow))
        return flow

    async def confirm(self, user_id: str) -> AuthFlow:
        """В моке — автоматическое подтверждение. В реальном SDK — валидация кода."""
        stored = await self._store.get(f"auth:{user_id}")
        if not stored:
            stored = {"user_id": user_id, "platform": "unknown", "state": "pending", "platform_user_id": None}

        stored["state"] = "confirmed"
        stored["platform_user_id"] = f"plt_{user_id}"
        await self._store.set(f"auth:{user_id}", stored)
        return _from_dict(stored)

    async def is_authenticated(self, user_id: str) -> bool:
        stored = await self._store.get(f"auth:{user_id}")
        return stored is not None and stored.get("state") == "confirmed"
