package user

import (
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
	"gorm.io/gorm"
)

// User specific permissions (data-level or direct assignment)

type GetPermissionsReq struct {
	UserID string  `src:"path@user_id" desc:"User ID"`
	Scope  *string `json:"scope" src:"query" desc:"Scope"`
}

func getPermissions(x *vigo.X, req *GetPermissionsReq) ([]models.Permission, error) {
	var permissions []models.Permission
	query := cfg.DB().Where("user_id = ?", req.UserID)

	if req.Scope != nil {
		query = query.Where("scope = ?", *req.Scope)
	}

	if err := query.Find(&permissions).Error; err != nil {
		return nil, vigo.ErrDatabase.WithError(err)
	}
	return permissions, nil
}

type UpdatePermissionsReq struct {
	UserID        string   `src:"path@user_id" desc:"User ID"`
	PermissionIDs []string `json:"permission_ids" src:"json" desc:"List of Permission IDs"`
	Scope         string   `json:"scope" src:"json" default:"default" desc:"Scope"`
}

func updatePermissions(x *vigo.X, req *UpdatePermissionsReq) error {
	var user models.User
	if err := cfg.DB().First(&user, "id = ?", req.UserID).Error; err != nil {
		return vigo.ErrNotFound
	}

	return cfg.DB().Transaction(func(tx *gorm.DB) error {
		// Delete existing user-specific permissions for this scope
		if err := tx.Where("user_id = ? AND scope = ?", req.UserID, req.Scope).Delete(&models.Permission{}).Error; err != nil {
			return err
		}

		// Add new permissions
		if len(req.PermissionIDs) > 0 {
			permissions := make([]models.Permission, 0, len(req.PermissionIDs))
			for _, pid := range req.PermissionIDs {
				permissions = append(permissions, models.Permission{
					Scope:        req.Scope,
					UserID:       &req.UserID,
					PermissionID: pid,
					Level:        7, // Default to Admin level
				})
			}
			if err := tx.Create(&permissions).Error; err != nil {
				return err
			}
		}
		return nil
	})
}
