package api

import (
	"context"
	"fmt"
	"net/http"
)

func (h APIHandler) OAuth2Callback(w http.ResponseWriter, r *http.Request) {
	oauth2Token, err := h.idp.OAuth2Config.Exchange(context.Background(), r.URL.Query().Get("code"))
	if err != nil {
		fmt.Println("Exchange error")
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// Extract the ID Token from OAuth2 token.
	rawIDToken, ok := oauth2Token.Extra("id_token").(string)
	if !ok {
		fmt.Println("issue retrieving token")
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	_, err = h.idp.TokenVerifier.Verify(context.Background(), rawIDToken)
	if err != nil {
		fmt.Println("not able to verify token")
		fmt.Println(err)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
	session.Values["idtoken"] = rawIDToken

	redirect := "/app/"

	if session.Values["redirect"] != nil && session.Values["redirect"] != "" {
		redirect = session.Values["redirect"].(string)
		delete(session.Values, "redirect")
	}

	if err = session.Save(r, w); err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, redirect, http.StatusFound)
}
