from rest_framework import viewsets

from warehouse.models import Warehouse, Stock
from .models import Product, Employee, Position, StorageLocation, Contractor, SupplyContract, Truck, Inventory
from django.http import JsonResponse
from .models import Inventory
from .serializers import (
    ProductSerializer, EmployeeSerializer, PositionSerializer,
    StorageLocationSerializer, ContractorSerializer, SupplyContractSerializer, TruckSerializer
)

def conduct_inventory(request, warehouse_id):
    warehouse = Warehouse.objects.get(id=warehouse_id)
    stock_items = Stock.objects.filter(location__warehouse=warehouse)

    inventory_results = []
    for stock_item in stock_items:
        recorded_quantity = stock_item.quantity
        # Симуляция фактического количества (можно заменить на ввод пользователя)
        actual_quantity = recorded_quantity - 5  # Пример: уменьшение на 5 для теста
        inventory = Inventory.objects.create(
            warehouse=warehouse,
            storage_location=stock_item.location,
            product=stock_item.product,
            actual_quantity=actual_quantity,
            recorded_quantity=recorded_quantity,
        )
        inventory_results.append(inventory)

    return JsonResponse({
        "message": "Инвентаризация завершена",
        "results": [str(result) for result in inventory_results],
    })

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer


class EmployeeViewSet(viewsets.ModelViewSet):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer


class PositionViewSet(viewsets.ModelViewSet):
    queryset = Position.objects.all()
    serializer_class = PositionSerializer


class StorageLocationViewSet(viewsets.ModelViewSet):
    queryset = StorageLocation.objects.all()
    serializer_class = StorageLocationSerializer


class ContractorViewSet(viewsets.ModelViewSet):
    queryset = Contractor.objects.all()
    serializer_class = ContractorSerializer


class SupplyContractViewSet(viewsets.ModelViewSet):
    queryset = SupplyContract.objects.all()
    serializer_class = SupplyContractSerializer


class TruckViewSet(viewsets.ModelViewSet):
    queryset = Truck.objects.all()
    serializer_class = TruckSerializer