package com.example.hrlab.integration; import com.example.hrlab.common.JsonUtils; import com.example.hrlab.security.HmacService; import java.util.Map; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service public class IntegrationEventService { private final JdbcTemplate jdbcTemplate; private final HmacService hmacService; public IntegrationEventService(JdbcTemplate jdbcTemplate, HmacService hmacService) { this.jdbcTemplate = jdbcTemplate; this.hmacService = hmacService; } public Long createEvent(String eventType, String businessKey, Map payload) { String json = JsonUtils.toJson(payload); try { return jdbcTemplate.queryForObject(""" INSERT INTO integration_events(event_type, business_key, payload_json, signature, status) VALUES (?, ?, ?::jsonb, ?, 'PENDING') RETURNING id """, Long.class, eventType, businessKey, json, hmacService.sign(json)); } catch (DataIntegrityViolationException ex) { return jdbcTemplate.queryForObject(""" SELECT id FROM integration_events WHERE event_type = ? AND business_key = ? """, Long.class, eventType, businessKey); } } }