package com.goldenchart.controller;

import com.goldenchart.dto.FcmTokenDto;
import com.goldenchart.service.FcmPushService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/fcm")
@RequiredArgsConstructor
public class FcmController {

    private final FcmPushService fcmPushService;

    private Long userId(Map<String, String> h) {
        String v = h.get("x-user-id");
        return v != null ? Long.parseLong(v) : null;
    }

    private String deviceId(Map<String, String> h) {
        return h.getOrDefault("x-device-id", "anonymous");
    }

    @PostMapping("/token")
    public ResponseEntity<Void> register(@RequestHeader Map<String, String> h,
                                         @RequestBody FcmTokenDto body) {
        fcmPushService.registerToken(
                body.getUserId() != null ? body.getUserId() : userId(h),
                body.getDeviceId() != null ? body.getDeviceId() : deviceId(h),
                body.getToken());
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/token")
    public ResponseEntity<Void> delete(@RequestHeader Map<String, String> h) {
        fcmPushService.deleteByDevice(deviceId(h));
        return ResponseEntity.ok().build();
    }

    @PostMapping("/test")
    public ResponseEntity<Map<String, Object>> test(@RequestHeader Map<String, String> h) {
        fcmPushService.sendTest(userId(h), deviceId(h));
        return ResponseEntity.ok(Map.of(
                "ok", true,
                "available", fcmPushService.isAvailable()
        ));
    }

    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> status() {
        return ResponseEntity.ok(Map.of("available", fcmPushService.isAvailable()));
    }
}
