package es.tatvil.taiageweb.controlador;

import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.Event;
import com.stripe.model.checkout.Session;
import com.stripe.net.Webhook;
import es.tatvil.taiageweb.servicio.UsuarioService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class WebhookController {

    @Value("${stripe.webhook-secret}")
    private String webhookSecret;

    private final UsuarioService usuarioService;

    public WebhookController(UsuarioService usuarioService) {
        this.usuarioService = usuarioService;
    }

    @PostMapping("/webhook/stripe")
    public ResponseEntity<String> stripeWebhook(
            @RequestBody String payload,
            @RequestHeader("Stripe-Signature") String sigHeader) {

        Event event;
        try {
            event = Webhook.constructEvent(payload, sigHeader, webhookSecret);
        } catch (SignatureVerificationException e) {
            return ResponseEntity.badRequest().body("Firma inválida");
        }

        if ("checkout.session.completed".equals(event.getType())) {
            event.getDataObjectDeserializer().getObject().ifPresent(obj -> {
                Session session = (Session) obj;
                String refId = session.getClientReferenceId();
                if (refId != null) {
                    try {
                        Long userId = Long.parseLong(refId);
                        usuarioService.darAccesoPagado(userId);
                    } catch (NumberFormatException ignored) {
                    }
                }
            });
        }

        return ResponseEntity.ok("ok");
    }
}
