package com.petshop.backend.service;

import com.petshop.backend.dto.purchaseorder.PurchaseOrderResponse;
import com.petshop.backend.entity.PurchaseOrder;
import com.petshop.backend.entity.StoreLocation;
import com.petshop.backend.exception.ResourceNotFoundException;
import com.petshop.backend.repository.PurchaseOrderRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class PurchaseOrderService {

    private final PurchaseOrderRepository purchaseOrderRepository;

    public PurchaseOrderService(PurchaseOrderRepository purchaseOrderRepository) {
        this.purchaseOrderRepository = purchaseOrderRepository;
    }

    public Page<PurchaseOrderResponse> getAllPurchaseOrders(String query, Long storeId, Pageable pageable) {
        String normalizedQuery = normalizeFilter(query);
        Page<PurchaseOrder> purchaseOrders = purchaseOrderRepository.searchPurchaseOrders(normalizedQuery, storeId, pageable);
        return purchaseOrders.map(this::mapToResponse);
    }

    public PurchaseOrderResponse getPurchaseOrderById(Long id) {
        PurchaseOrder purchaseOrder = purchaseOrderRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("PurchaseOrder not found with id: " + id));
        return mapToResponse(purchaseOrder);
    }

    private String normalizeFilter(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }

    private PurchaseOrderResponse mapToResponse(PurchaseOrder purchaseOrder) {
        StoreLocation store = purchaseOrder.getStore();
        return new PurchaseOrderResponse(
            purchaseOrder.getPurchaseOrderId(),
            purchaseOrder.getSupplier().getSupId(),
            purchaseOrder.getSupplier().getSupCompany(),
            store != null ? store.getStoreId() : null,
            store != null ? store.getStoreName() : null,
            purchaseOrder.getOrderDate(),
            purchaseOrder.getCreatedAt(),
            purchaseOrder.getUpdatedAt()
        );
    }
}
