package web

import (
	"log/slog"
	"net/http"

	"backend/internal/auth"
	"backend/internal/db/sqlc"
	"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
			}
		}

		sidebarTablos, err := deps.Queries.ListTablosByUser(r.Context(), user.ID)
		if err != nil {
			slog.Default().Error("account providers: ListTablosByUser failed", "user_id", user.ID, "err", err)
			sidebarTablos = []sqlc.Tablo{}
		}
		if sidebarTablos == nil {
			sidebarTablos = []sqlc.Tablo{}
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_ = templates.AccountProvidersPage(user, statuses, csrf.Token(r), "/", sidebarTablos,
			"Linked Providers",
			[]templates.BreadcrumbItem{{Label: "Linked Providers", Href: ""}},
		).Render(r.Context(), w)
	}
}
