"""Services."""
from __future__ import annotations
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from app.events.publisher import get_event_publisher
from app.events.types import BeautyBusinessEventType
from app.models.types import AuditAction
from app.services.audit_service import AuditService
from app.validators import validate_code
from shared.exceptions import AppError, NotFoundError
from shared.security import CurrentUser

def _actor(actor):
    return actor.user_id if actor else None


from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession

from app.events.publisher import get_event_publisher
from app.events.types import BeautyBusinessEventType
from app.models.customers import CustomerProfile
from app.models.types import AuditAction
from app.repositories.customers import CustomerProfileRepository
from app.schemas.customers import CustomerProfileCreate
from app.services.audit_service import AuditService
from app.validators import validate_code
from shared.exceptions import AppError, NotFoundError
from shared.security import CurrentUser


def _actor(actor: CurrentUser | None) -> str | None:
    return actor.user_id if actor else None


class CustomerProfileService:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session
        self.repo = CustomerProfileRepository(session)
        self.audit = AuditService(session)
        self.events = get_event_publisher()

    async def create(self, tenant_id: UUID, body: CustomerProfileCreate, *, actor: CurrentUser | None = None) -> CustomerProfile:
        code = validate_code(body.code)
        if await self.repo.get_by_code(tenant_id, code):
            raise AppError("کد تکراری است", error_code="duplicate_code", status_code=409)
        data = body.model_dump()
        entity = CustomerProfile(tenant_id=tenant_id, **data, created_by=_actor(actor), updated_by=_actor(actor))
        await self.repo.add(entity)
        await self.audit.record(
            tenant_id=tenant_id,
            entity_type="customer_profile",
            entity_id=entity.id,
            action=AuditAction.CREATE,
            actor_user_id=_actor(actor),
            changes=data,
        )
        self.events.publish(
            event_type=BeautyBusinessEventType.CUSTOMER_PROFILE_CREATED,
            aggregate_type="customer_profile",
            aggregate_id=entity.id,
            tenant_id=tenant_id,
            payload={"id": str(entity.id)},
        )
        await self.session.commit()
        await self.session.refresh(entity)
        return entity

    async def get(self, tenant_id: UUID, entity_id: UUID) -> CustomerProfile:
        entity = await self.repo.get(tenant_id, entity_id)
        if entity is None:
            raise NotFoundError("مورد یافت نشد")
        return entity

    async def list(self, tenant_id: UUID, *, offset: int = 0, limit: int = 20):
        return await self.repo.list_by_tenant(tenant_id, offset=offset, limit=limit)

    async def soft_delete(self, tenant_id: UUID, entity_id: UUID, *, actor: CurrentUser | None = None) -> CustomerProfile:
        entity = await self.get(tenant_id, entity_id)
        await self.repo.soft_delete(entity, deleted_by=_actor(actor))
        await self.audit.record(
            tenant_id=tenant_id,
            entity_type="customer_profile",
            entity_id=entity.id,
            action=AuditAction.DELETE,
            actor_user_id=_actor(actor),
        )
        await self.session.commit()
        await self.session.refresh(entity)
        return entity
