package com.honey.honey.controller;

import com.honey.honey.dto.ExternalDepositWebhookRequest;
import com.honey.honey.service.PaymentService;
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.*;

/**
 * Controller for 3rd party deposit completion webhook.
 * Path: POST /api/deposit_webhook/{token}. Token must match app.deposit-webhook.token (APP_DEPOSIT_WEBHOOK_TOKEN).
 * No session auth; token in path only. Set the token on VPS via environment variable.
 */
@Slf4j
@RestController
@RequestMapping("/api/deposit_webhook")
@RequiredArgsConstructor
public class DepositWebhookController {

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

    private final PaymentService paymentService;

    /**
     * Called by 3rd party when a user's crypto deposit was successful.
     * Body: user_id (internal id from db_users_a), usd_amount (decimal, e.g. 1.45).
     */
    @PostMapping("/{token}")
    public ResponseEntity<Void> onDepositCompleted(
            @PathVariable String token,
            @RequestBody ExternalDepositWebhookRequest request) {
        if (expectedToken.isEmpty() || !expectedToken.equals(token)) {
            log.warn("Deposit webhook rejected: invalid token");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        if (request == null || request.getUserId() == null || request.getUsdAmount() == null) {
            return ResponseEntity.badRequest().build();
        }
        try {
            paymentService.processExternalDepositCompletion(
                    request.getUserId(),
                    request.getUsdAmount());
            return ResponseEntity.ok().build();
        } catch (IllegalArgumentException e) {
            log.warn("Deposit webhook rejected: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("Deposit webhook error: userId={}, usdAmount={}", request.getUserId(), request.getUsdAmount(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
