package auth

import (
	"context"
	"database/sql"
	"log"
	"net/http"

	ory "github.com/ory/client-go"

	"decor-by-hannahs/internal/db"
)

func AdminMiddleware(oryClient *ory.APIClient, queries *db.Queries) func(http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			cookies := r.Header.Get("Cookie")
			session, _, err := oryClient.FrontendAPI.ToSession(r.Context()).Cookie(cookies).Execute()
			
			if err != nil || session == nil || session.Active == nil || !*session.Active {
				http.Error(w, "Unauthorized - Please log in", http.StatusUnauthorized)
				return
			}

			email := getEmailFromSession(session)
			if email == "" {
				http.Error(w, "No email in session", http.StatusBadRequest)
				return
			}

			oryID := sql.NullString{String: session.Identity.Id, Valid: true}
			user, err := queries.GetUserByOryID(r.Context(), oryID)
			if err != nil {
				http.Error(w, "User not found", http.StatusUnauthorized)
				return
			}

			if !user.IsAdmin.Bool {
				log.Printf("Non-admin user %s attempted to access admin area", email)
				http.Error(w, "Forbidden - Admin access required", http.StatusForbidden)
				return
			}

			ctx := context.WithValue(r.Context(), "user", user)
			next.ServeHTTP(w, r.WithContext(ctx))
		}
	}
}
