package com.honey.honey.controller;

import com.honey.honey.dto.NotifyBroadcastRequest;
import com.honey.honey.service.NotificationBroadcastService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * Public API to trigger or stop notification broadcast. Token in path; no secrets in codebase.
 * Set APP_NOTIFY_BROADCAST_TOKEN on VPS.
 */
@Slf4j
@RestController
@RequestMapping("/api/notify_broadcast")
@RequiredArgsConstructor
public class NotifyBroadcastController {

    @Value("${app.notify-broadcast.token:}")
    private String expectedToken;

    private final NotificationBroadcastService notificationBroadcastService;

    @PostMapping("/{token}")
    public ResponseEntity<Void> start(
            @PathVariable String token,
            @RequestBody(required = false) NotifyBroadcastRequest body) {
        if (expectedToken.isEmpty() || !expectedToken.equals(token)) {
            log.warn("Notify broadcast rejected: invalid token");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        NotifyBroadcastRequest req = body != null ? body : new NotifyBroadcastRequest();
        notificationBroadcastService.runBroadcast(
                req.getMessage(),
                req.getImageUrl(),
                req.getVideoUrl(),
                req.getUserIdFrom(),
                req.getUserIdTo(),
                req.getButtonText(),
                req.getIgnoreBlocked());
        return ResponseEntity.accepted().build();
    }

    @PostMapping("/{token}/stop")
    public ResponseEntity<Void> stop(@PathVariable String token) {
        if (expectedToken.isEmpty() || !expectedToken.equals(token)) {
            log.warn("Notify broadcast stop rejected: invalid token");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        notificationBroadcastService.requestStop();
        return ResponseEntity.ok().build();
    }
}
