"""APIهای مدیریت پلن‌ها و اتصال قابلیت به پلن."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination
from app.core.security import require_authenticated, require_platform_admin
from app.schemas.plan import (
    PlanCreate,
    PlanFeatureCreate,
    PlanFeatureRead,
    PlanRead,
)
from app.services.plan_service import PlanService
from shared.pagination import Page, PaginationParams

router = APIRouter(prefix="/plans", tags=["plans"])


@router.post("", response_model=PlanRead, status_code=status.HTTP_201_CREATED)
async def create_plan(
    payload: PlanCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> PlanRead:
    plan = await PlanService(db).create_plan(payload)
    return PlanRead.model_validate(plan)


@router.get("", response_model=Page[PlanRead])
async def list_plans(
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> Page[PlanRead]:
    items, total = await PlanService(db).list_plans(
        offset=pagination.offset, limit=pagination.limit
    )
    return Page.create([PlanRead.model_validate(p) for p in items], total, pagination)


@router.post(
    "/{plan_id}/features",
    response_model=PlanFeatureRead,
    status_code=status.HTTP_201_CREATED,
)
async def attach_feature_to_plan(
    plan_id: UUID,
    payload: PlanFeatureCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> PlanFeatureRead:
    plan_feature = await PlanService(db).attach_feature(plan_id, payload)
    return PlanFeatureRead.model_validate(plan_feature)
