package web

import (
	"net/http"

	"backend/internal/auth"
	"backend/templates"

	"github.com/gorilla/csrf"
)

func AccountProvidersHandler(deps AuthDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		_, user, ok := auth.Authed(r.Context())
		if !ok {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}

		identities, err := deps.Queries.ListUserIdentitiesByUser(r.Context(), user.ID)
		if err != nil {
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}

		statuses := []templates.LinkedProviderStatus{
			{Name: "Google"},
		}
		for _, identity := range identities {
			switch identity.Provider {
			case "google":
				statuses[0].Connected = true
				statuses[0].Email = identity.Email
			}
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_ = templates.AccountProvidersPage(user, statuses, csrf.Token(r)).Render(r.Context(), w)
	}
}
