package de.szut.casino.security.oauth2.google;

import de.szut.casino.security.dto.AuthResponseDto;
import de.szut.casino.security.oauth2.github.GithubCallbackDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

@RestController
@RequestMapping("/oauth2/google")
public class GoogleController {
    private static final Logger logger = LoggerFactory.getLogger(GoogleController.class);

    @Value("${spring.security.oauth2.client.registration.google.client-id}")
    private String clientId;

    @Value("${spring.security.oauth2.client.provider.google.authorization-uri}")
    private String authorizationUri;

    @Value("${spring.security.oauth2.client.registration.google.redirect-uri}")
    private String redirectUri;

    private final GoogleService googleService;

    public GoogleController(GoogleService googleService) {
        this.googleService = googleService;
    }

    @GetMapping("/authorize")
    public RedirectView authorizeGoogle() {
        logger.info("Redirecting to Google for authorization");

        String authUrl = authorizationUri +
                "?client_id=" + clientId +
                "&redirect_uri=" + redirectUri +
                "&response_type=code" +
                "&scope=email profile";

        return new RedirectView(authUrl);
    }

    @PostMapping("/callback")
    public ResponseEntity<AuthResponseDto> googleCallback(@RequestBody GithubCallbackDto callbackDto) {
        String code = callbackDto.getCode();
        AuthResponseDto response = googleService.processGoogleCode(code);
        return ResponseEntity.ok(response);
    }
}
