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

import de.szut.casino.security.dto.AuthResponseDto;
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/github")
public class GitHubController {
    private static final Logger logger = LoggerFactory.getLogger(GitHubController.class);

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

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

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

    private final GitHubService githubService;

    public GitHubController(GitHubService githubService) {
        this.githubService = githubService;
    }

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

        String authUrl = authorizationUri +
                "?client_id=" + clientId +
                "&redirect_uri=" + redirectUri +
                "&scope=user:email,read:user";

        return new RedirectView(authUrl);
    }


    @PostMapping("/callback")
    public ResponseEntity<AuthResponseDto> githubCallback(@RequestBody GithubCallbackDto githubCallbackDto) {
        String code = githubCallbackDto.getCode();
        AuthResponseDto response = githubService.processGithubCode(code);
        return ResponseEntity.ok(response);
    }
}
