package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"

	"context"
	"log"
	"net/http"
	"ordr-api/dto"
	"ordr-api/queries"
)

func UserInDatabase(pool *pgxpool.Pool) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		conn, conn_err := pool.Acquire(ctx)
		if conn_err != nil {
			log.Printf("UserInDatabase(): ERROR: Failed to establish connection... %s", conn_err.Error())
			ctx.AbortWithStatus(http.StatusInternalServerError)
		}
		defer conn.Release()

		user_profile, _ := ctx.Get("user_profile")

		sub_id := user_profile.(dto.UserProfileResponse).Sub
		nickname := user_profile.(dto.UserProfileResponse).Nickname

		var count int
		query_err := conn.QueryRow(context.Background(), "SELECT COUNT(id) FROM ordr_user WHERE sub_id = $1", sub_id).Scan(&count)
		if query_err != nil {
			log.Println("UserInDatabase(): ERROR Failed to query for user count")
			ctx.AbortWithStatus(http.StatusInternalServerError)
			return
		}

		log.Printf("%d", count)

		if count == 0 {
			_, exec_err := conn.Exec(context.Background(), queries.USER_CREATE_QUERY, sub_id, nickname)

			if exec_err != nil {
				log.Printf("UserInDatabase(): ERROR Failed to create user... %s", exec_err.Error())
				ctx.AbortWithStatus(http.StatusInternalServerError)
				return
			}
		}
	}
}

func UserIsActive(pool *pgxpool.Pool) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		conn, conn_err := pool.Acquire(ctx)
		if conn_err != nil {
			log.Printf("UserIsActive(): ERROR: Failed to establish connection... %s", conn_err.Error())
			ctx.AbortWithStatus(http.StatusInternalServerError)
		}
		defer conn.Release()

		user_profile, _ := ctx.Get("user_profile")

		sub_id := user_profile.(dto.UserProfileResponse).Sub

		var active bool
		query_err := conn.QueryRow(context.Background(), "SELECT active FROM ordr_user WHERE sub_id=$1", sub_id).Scan(&active)
		if query_err != nil {
			log.Printf("UserIsActive: ERROR: Failed to query user... %s", query_err.Error())
		}

		if !active {
			ctx.AbortWithStatus(http.StatusUnauthorized)
		}
		ctx.Next()
	}
}
