package io.delphiplatform.api.v3.view;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

import io.delphiplatform.api.security.AuthService;
import io.delphiplatform.api.v2.model.AuthTokenRequestBody;
import io.delphiplatform.api.v2.model.AuthTokenResponseBody;

@Controller
@RequestMapping("${spring.data.rest.base-path:/v3}")
public class OauthApiController implements OauthApi {

    private final AuthService authService;

    @Autowired
    public OauthApiController(AuthService authService) {
        this.authService = authService;
    }

    public ResponseEntity<AuthTokenResponseBody> authPost(@Valid @RequestBody AuthTokenRequestBody body) {
        return authService.authenticate(body);
    }

    @Override
    public ResponseEntity<AuthTokenResponseBody> authPost(String clientId, String clientSecret, String audience,
        String grantType) {
        AuthTokenRequestBody body = AuthTokenRequestBody.builder()
            .clientId(clientId)
            .clientSecret(clientSecret)
            .grantType(grantType)
            .audience(audience)
            .build();
        return authService.authenticate(body);
    }
}
