package com.atomikos.examples.opentracing;

import java.sql.SQLException;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;

@RestController
@RequestMapping(path = "/account")
@Api(authorizations = @Authorization(value = "ItxApiKey", scopes = {}))
public class AccountController {

	private final JmsTemplate jmsTemplate;

	private final AccountRepository accountRepository;

	public AccountController(JmsTemplate jmsTemplate, AccountRepository accountRepository) {
		this.jmsTemplate = jmsTemplate;
		this.accountRepository = accountRepository;
	}
	
    @GetMapping("{username}")
    @Transactional
    @ApiOperation("Insert account and publish a jms message")
    public Account createAccount(@PathVariable String username) throws SQLException {
    	
		this.jmsTemplate.convertAndSend("accounts", username);
		Account created = this.accountRepository.save(new Account(username));
		if ("error".equals(username)) {
			throw new RuntimeException("Simulated error");
		}
		return created;
    }
}
