package com.mosquito.project.controller;

import com.mosquito.project.dto.RegisterCallbackRequest;
import com.mosquito.project.persistence.entity.ProcessedCallbackEntity;
import com.mosquito.project.persistence.repository.ProcessedCallbackRepository;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/callback")
public class CallbackController {

    private final ProcessedCallbackRepository processedCallbackRepository;
    private final com.mosquito.project.service.RewardQueue rewardQueue;

    public CallbackController(ProcessedCallbackRepository processedCallbackRepository, com.mosquito.project.service.RewardQueue rewardQueue) {
        this.processedCallbackRepository = processedCallbackRepository;
        this.rewardQueue = rewardQueue;
    }

    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid @RequestBody RegisterCallbackRequest request) {
        String trackingId = request.getTrackingId();
        if (processedCallbackRepository.existsById(trackingId)) {
            return ResponseEntity.ok().build();
        }
        ProcessedCallbackEntity e = new ProcessedCallbackEntity();
        e.setTrackingId(trackingId);
        e.setCreatedAt(java.time.OffsetDateTime.now(java.time.ZoneOffset.UTC));
        processedCallbackRepository.save(e);

        rewardQueue.enqueueReward(trackingId, request.getExternalUserId(), null);
        return ResponseEntity.ok().build();
    }
}

