from __future__ import annotations

from typing import TYPE_CHECKING, Protocol
from uuid import UUID

from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError

from core.db.base_repository import BaseRepository
from core.logging import get_logger
from models.profile import Profile

if TYPE_CHECKING:
    from sqlalchemy.ext.asyncio import AsyncSession

logger = get_logger("v1.profile.repository")


class ProfileRepository(Protocol):
    """Protocol defining the profile repository interface."""

    async def get_by_user_id(self, user_id: UUID) -> Profile | None:
        """Get profile by user ID."""
        ...

    async def get_by_username(self, username: str) -> Profile | None:
        """Get profile by username."""
        ...

    async def update_by_user_id(
        self, user_id: UUID, update_data: dict[str, str | None]
    ) -> Profile | None:
        """Update profile by user ID. Returns updated profile or None if not found."""
        ...


class SQLAlchemyProfileRepository(BaseRepository[Profile]):
    """SQLAlchemy implementation of ProfileRepository.

    Note: This repository only performs CRUD operations.
    - No commit (only flush) - service layer handles transactions
    - No auth logic - service layer handles authorization
    - No HTTP exceptions - returns None or raises SQLAlchemyError
    """

    def __init__(self, session: AsyncSession) -> None:
        super().__init__(session, Profile)

    async def get_by_user_id(self, user_id: UUID) -> Profile | None:
        try:
            return await self.get_by_id(user_id)
        except SQLAlchemyError:
            logger.exception("Profile lookup failed", user_id=str(user_id))
            raise

    async def get_by_username(self, username: str) -> Profile | None:
        try:
            stmt = (
                select(Profile)
                .where(Profile.username == username)
                .where(Profile.deleted_at.is_(None))
                .order_by(Profile.created_at.asc())
                .limit(1)
            )
            result = await self._session.execute(stmt)
            return result.scalar_one_or_none()
        except SQLAlchemyError:
            logger.exception("Profile lookup failed", username=username)
            raise

    async def update_by_user_id(
        self, user_id: UUID, update_data: dict[str, str | None]
    ) -> Profile | None:
        if not update_data:
            return await self.get_by_user_id(user_id)

        try:
            return await self.update_by_id(user_id, update_data)
        except SQLAlchemyError:
            logger.exception("Profile update failed", user_id=str(user_id))
            raise
