package com.smyhub.store.mengyastorebackendjava.controller;

import com.smyhub.store.mengyastorebackendjava.dto.response.ApiResponse;
import com.smyhub.store.mengyastorebackendjava.dto.response.ProductResponse;
import com.smyhub.store.mengyastorebackendjava.service.ProductService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

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

    private final ProductService productService;

    @GetMapping("/products")
    public ResponseEntity<ApiResponse<List<ProductResponse>>> listProducts() {
        return ResponseEntity.ok(ApiResponse.ok(productService.listPublicProducts()));
    }

    @PostMapping("/products/{id}/view")
    public ResponseEntity<ApiResponse<Map<String, Object>>> recordView(
            @PathVariable String id,
            HttpServletRequest request) {
        String fingerprint = buildFingerprint(request);
        ProductResponse p = productService.recordView(id, fingerprint);
        return ResponseEntity.ok(ApiResponse.ok(Map.of(
                "id", p.getId(),
                "viewCount", p.getViewCount(),
                "counted", true
        )));
    }

    private String buildFingerprint(HttpServletRequest request) {
        String ip = getClientIp(request);
        String ua = nvl(request.getHeader("User-Agent"));
        String lang = nvl(request.getHeader("Accept-Language"));
        return ip + "|" + ua + "|" + lang;
    }

    private String getClientIp(HttpServletRequest request) {
        String forwarded = request.getHeader("X-Forwarded-For");
        if (forwarded != null && !forwarded.isBlank()) {
            return forwarded.split(",")[0].strip();
        }
        return request.getRemoteAddr();
    }

    private String nvl(String s) {
        return s != null ? s.strip() : "";
    }
}
