"""
标记库存变动记录完成的视图
"""

from rest_framework import status, views
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
import logging

from drf_spectacular.utils import extend_schema
from stock import models as stock_models, services as stock_services

from .mixins import StockChangeViewMixin

logger = logging.getLogger(__name__)


class FinishStockChangeView(StockChangeViewMixin, views.APIView):
    """标记库存变动记录为完成"""

    permission_classes = [IsAuthenticated]

    @extend_schema(
        tags=['完成出入库'],
        responses={200: dict},
        summary='手动完成库存变动记录',
        description='根据出入库单ID手动触发库存扣减、快照写入，并标记为完成'
    )
    def post(self, request, record_id: int):
        if not self.check_employee_permission(request):
            return self.permission_error_response('无权限操作')

        merchant_id = self.get_merchant_id(request)
        if merchant_id is None:
            return self.permission_error_response('无权限操作')

        try:
            record = stock_models.StockChangeRecord.objects.select_related(
                'warehouse', 'created_by'
            ).get(id=record_id)
        except stock_models.StockChangeRecord.DoesNotExist:
            return self.not_found_response(f'库存变动记录ID {record_id} 不存在')

        if record.merchant_id != merchant_id:
            return self.permission_error_response('无权操作该库存变动记录')

        if not self.validate_warehouse_visibility(record.warehouse_id, request):
            return self.permission_error_response('该库存变动记录的仓库对当前用户不可见')

        try:
            stock_services.make_stock_change_completed(record)
            record.refresh_from_db()

            message = (
                '库存变动记录已标记为完成'
                if record.is_finished else
                '库存变动记录仍未完成，请检查明细'
            )
            status_flag = 'success' if record.is_finished else 'pending'

            logger.info(
                '用户 %s 手动完成库存变动记录 %s（状态：%s）',
                request.user.username,
                record.id,
                status_flag,
            )

            return Response({
                'status': status_flag,
                'message': message,
                'stock_change_record': self.build_record_data(record),
            }, status=status.HTTP_200_OK)
        except Exception as exc:
            logger.error(
                '手动完成库存变动记录 %s 失败: %s',
                record_id,
                str(exc),
                exc_info=True,
            )
            return Response({
                'error': '标记库存变动记录失败',
                'message': str(exc),
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

