"""Repository مربوط به Plan، Feature و PlanFeature."""
from __future__ import annotations

from typing import Sequence
from uuid import UUID

from sqlalchemy import func, select

from app.models.plan import Feature, Plan, PlanFeature
from app.repositories.base import BaseRepository


class PlanRepository(BaseRepository[Plan]):
    model = Plan

    async def get_by_code(self, code: str) -> Plan | None:
        stmt = select(Plan).where(Plan.code == code)
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

    async def code_exists(self, code: str) -> bool:
        stmt = select(func.count()).select_from(Plan).where(Plan.code == code)
        result = await self.session.execute(stmt)
        return int(result.scalar_one()) > 0


class FeatureRepository(BaseRepository[Feature]):
    model = Feature

    async def get_by_key(self, feature_key: str) -> Feature | None:
        stmt = select(Feature).where(Feature.feature_key == feature_key)
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

    async def key_exists(self, feature_key: str) -> bool:
        stmt = select(func.count()).select_from(Feature).where(
            Feature.feature_key == feature_key
        )
        result = await self.session.execute(stmt)
        return int(result.scalar_one()) > 0


class PlanFeatureRepository(BaseRepository[PlanFeature]):
    model = PlanFeature

    async def get(self, plan_id: UUID, feature_id: UUID) -> PlanFeature | None:
        stmt = select(PlanFeature).where(
            PlanFeature.plan_id == plan_id,
            PlanFeature.feature_id == feature_id,
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

    async def list_by_plan(self, plan_id: UUID) -> Sequence[PlanFeature]:
        stmt = select(PlanFeature).where(PlanFeature.plan_id == plan_id)
        result = await self.session.execute(stmt)
        return result.scalars().all()
