package com.nebula.erp.product.controller;

import com.nebula.erp.product.model.Image;
import com.nebula.erp.product.model.Product;
import com.nebula.erp.product.service.PublicProductService;
import com.nebula.erp.product.utility.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/public")
public class PublicProductController {

    @Autowired
    private PublicProductService publicProductService;

    @Value("${images.url}")
    private String imagesUrl;

    @Value("${image.storage.location}")
    private String imageStorageLocation;

    // GET /api/public/products?tenant=biocom_Tenant&page=1&size=100
    @GetMapping("/products")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getProductsByTenant(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "100") int size,
            @RequestParam(value = "tenant", required = true) String tenant) {
        try {
            Page<Product> productPage = publicProductService.getProductsByTenant(page, size, tenant);

            List<Map<String, Object>> products = productPage.getContent().stream()
                    .map(this::prepareProductResponse)
                    .collect(Collectors.toList());

            Map<String, Object> pagination = new LinkedHashMap<>();
            pagination.put("current_page", productPage.getNumber() + 1);
            pagination.put("per_page", productPage.getSize());
            pagination.put("total", productPage.getTotalElements());
            pagination.put("last_page", productPage.getTotalPages());
            pagination.put("next_page_url", productPage.hasNext() ? "/api/public/products?page=" + (page + 1) + "&size=" + size + "&tenant=" + tenant : null);
            pagination.put("prev_page_url", productPage.hasPrevious() ? "/api/public/products?page=" + (page - 1) + "&size=" + size + "&tenant=" + tenant : null);

            Map<String, Object> data = new LinkedHashMap<>();
            data.put("pagination", pagination);
            data.put("items", products);

            return ResponseEntity.ok(new ApiResponse<>("Success", HttpStatus.OK.value(), "Products retrieved successfully.", data));

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>("Error", HttpStatus.BAD_REQUEST.value(), e.getMessage(), null));
        }
    }

    private Map<String, Object> prepareProductResponse(Product productData) {
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("id", productData.getId());
        data.put("code", productData.getCode());
        data.put("name", productData.getName());
        data.put("form", productData.getForm());
        data.put("min_stock", productData.getMin_stock());
        if (productData.getBrand() != null) {
            data.put("brand_id", productData.getBrand().getId());
            data.put("brand_name", productData.getBrand().getName());
        }
        if (productData.getCategory() != null) {
            data.put("category_id", productData.getCategory().getId());
            data.put("category_name", productData.getCategory().getName());
        }
        return data;
    }
}