"""سرویس مدیریت ServiceRegistry (ثبت سرویس‌های داخلی آینده)."""
from __future__ import annotations

from typing import Sequence
from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession

from app.models.enums import ServiceStatus
from app.models.registry import ServiceRegistry
from app.repositories.registry import ServiceRegistryRepository
from app.schemas.service_registry import ServiceCreate
from shared.exceptions import ConflictError, NotFoundError


class ServiceRegistryService:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session
        self.repo = ServiceRegistryRepository(session)

    async def create(self, data: ServiceCreate) -> ServiceRegistry:
        if await self.repo.get_by_key(data.service_key) is not None:
            raise ConflictError(
                f"service_key تکراری است: {data.service_key}",
                error_code="service_key_taken",
            )
        service = ServiceRegistry(
            service_key=data.service_key,
            name=data.name,
            base_url=data.base_url,
            health_check_url=data.health_check_url,
            status=data.status,
        )
        await self.repo.add(service)
        await self.session.commit()
        await self.session.refresh(service)
        return service

    async def list(self, *, offset: int, limit: int) -> tuple[Sequence[ServiceRegistry], int]:
        items = await self.repo.list(offset=offset, limit=limit)
        total = await self.repo.count()
        return items, total

    async def update_status(self, service_id: UUID, status: ServiceStatus) -> ServiceRegistry:
        service = await self.repo.get(service_id)
        if service is None:
            raise NotFoundError(f"سرویس یافت نشد: {service_id}")
        service.status = status
        await self.session.commit()
        await self.session.refresh(service)
        return service
