package middleware

import (
	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"web-qudo-be/app/middleware"
)

// AddClientFilter adds client_id filter to GORM query
func AddClientFilter(db *gorm.DB, c *fiber.Ctx) *gorm.DB {
	if c == nil {
		return db
	}
	clientID := middleware.GetClientID(c)
	if clientID != nil {
		return db.Where("client_id = ?", clientID)
	}
	return db
}

// SetClientID sets client_id in the given struct if it has a ClientId field
func SetClientID(c *fiber.Ctx, model interface{}) {
	if c == nil {
		return
	}
	clientID := middleware.GetClientID(c)
	if clientID != nil {
		// Use reflection to set ClientId field if it exists
		if setter, ok := model.(interface{ SetClientID(*uuid.UUID) }); ok {
			setter.SetClientID(clientID)
		}
	}
}

// ValidateClientAccess validates if the current client has access to the resource
func ValidateClientAccess(db *gorm.DB, c *fiber.Ctx, tableName string, resourceID interface{}) error {
	if c == nil {
		return nil // Skip validation for background jobs
	}
	clientID := middleware.GetClientID(c)
	if clientID == nil {
		return fiber.NewError(fiber.StatusUnauthorized, "Client not authenticated")
	}

	var count int64
	if err := db.Table(tableName).Where("id = ? AND client_id = ?", resourceID, clientID).Count(&count).Error; err != nil {
		return err
	}

	if count == 0 {
		return fiber.NewError(fiber.StatusForbidden, "Access denied to this resource")
	}

	return nil
}
