package middlewares

import (
	"nearle/db"
	"nearle/models"

	"github.com/gofiber/fiber/v2"
)

type RolePayload struct {
	Roleid int `json:"roleid"`



}

func RoleCheckMiddleware(allowedRoles ...int) fiber.Handler {
	return func(c *fiber.Ctx) error {
		var user models.User

		if err := c.BodyParser(&user); err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"status":  false,
				"code":    400,
				"message": "Invalid request body",
			})
		}

		var uid, dbRoleId int
		var status, dbPassword string
		var query string

		if user.Authname != "" {
			query = `SELECT userid, password, status, roleid FROM app_users WHERE authname = ? AND configid = ?`
			db.DB.Raw(query, user.Authname, user.Configid).Row().Scan(&uid, &dbPassword, &status, &dbRoleId)
		} else if user.Contactno != "" {
			query = `SELECT userid, password, status, roleid FROM app_users WHERE contactno = ? AND configid = ?`
			db.DB.Raw(query, user.Contactno, user.Configid).Row().Scan(&uid, &dbPassword, &status, &dbRoleId)
		} else {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"status":  false,
				"code":    400,
				"message": "authname or contactno required",
			})
		}

		// No user found
		if uid == 0 {
			return c.Status(fiber.StatusOK).JSON(fiber.Map{
				"status":     false,
				"code":       409,
				"message":    "Invalid Email",
				"tenantform": true,
			})
		}

		// Inactive user
		if status == "InActive" {
			return c.Status(fiber.StatusOK).JSON(fiber.Map{
				"status":  false,
				"code":    403,
				"message": "Inactive Account. Contact admin.",
			})
		}

		// Check allowed role
		allowed := false
		for _, r := range allowedRoles {
			if dbRoleId == r {
				allowed = true
				break
			}
		}

		if !allowed {
			return c.Status(fiber.StatusOK).JSON(fiber.Map{
				"status":  false,
				"code":    403,
				"message": "Unauthorized role",
			})
		}

		// Store user data in context
		c.Locals("uid", uid)
		c.Locals("password", dbPassword)

		return c.Next()
	}
}
