package role

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

type GetPermissionsReq struct {
	RoleID string `src:"path@id" desc:"Role ID"`
}

func getPermissions(x *vigo.X, req *GetPermissionsReq) ([]models.Permission, error) {
	var permissions []models.Permission
	if err := cfg.DB().Where("role_id = ?", req.RoleID).Find(&permissions).Error; err != nil {
		return nil, vigo.ErrDatabase.WithError(err)
	}
	return permissions, nil
}

type UpdatePermissionsReq struct {
	RoleID        string   `src:"path@id" desc:"Role ID"`
	Scope         string   `json:"scope" src:"query" default:"vb" desc:"Permission Scope"`
	PermissionIDs []string `json:"permission_ids" src:"json" desc:"List of Permission IDs"`
}

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

	if role.IsSystem {
		return vigo.NewError("cannot modify permissions of system role").WithCode(40300)
	}

	return cfg.DB().Transaction(func(tx *gorm.DB) error {
		// Delete existing permissions for this role AND scope
		if err := tx.Where("role_id = ? AND scope = ?", req.RoleID, 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,
					RoleID:       &req.RoleID,
					PermissionID: pid,
					Level:        7, // Default to Admin level to ensure it passes checks
				})
			}
			if err := tx.Create(&permissions).Error; err != nil {
				return err
			}
		}
		return nil
	})
}
