"""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.staff import StaffProfile
from app.models.types import AuditAction
from app.repositories.staff import StaffProfileRepository
from app.schemas.staff import StaffProfileCreate
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 StaffProfileService:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session
        self.repo = StaffProfileRepository(session)
        self.audit = AuditService(session)
        self.events = get_event_publisher()

    async def create(self, tenant_id: UUID, body: StaffProfileCreate, *, actor: CurrentUser | None = None) -> StaffProfile:
        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 = StaffProfile(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="staff_profile",
            entity_id=entity.id,
            action=AuditAction.CREATE,
            actor_user_id=_actor(actor),
            changes=data,
        )
        self.events.publish(
            event_type=BeautyBusinessEventType.STAFF_PROFILE_CREATED,
            aggregate_type="staff_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) -> StaffProfile:
        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) -> StaffProfile:
        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="staff_profile",
            entity_id=entity.id,
            action=AuditAction.DELETE,
            actor_user_id=_actor(actor),
        )
        await self.session.commit()
        await self.session.refresh(entity)
        return entity


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.staff import CommissionRule
from app.models.types import AuditAction
from app.repositories.staff import CommissionRuleRepository
from app.schemas.staff import CommissionRuleCreate
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 CommissionRuleService:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session
        self.repo = CommissionRuleRepository(session)
        self.audit = AuditService(session)
        self.events = get_event_publisher()

    async def create(self, tenant_id: UUID, body: CommissionRuleCreate, *, actor: CurrentUser | None = None) -> CommissionRule:
        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 = CommissionRule(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="commission_rule",
            entity_id=entity.id,
            action=AuditAction.CREATE,
            actor_user_id=_actor(actor),
            changes=data,
        )
        self.events.publish(
            event_type=BeautyBusinessEventType.COMMISSION_RULE_CREATED,
            aggregate_type="commission_rule",
            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) -> CommissionRule:
        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) -> CommissionRule:
        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="commission_rule",
            entity_id=entity.id,
            action=AuditAction.DELETE,
            actor_user_id=_actor(actor),
        )
        await self.session.commit()
        await self.session.refresh(entity)
        return entity
