package role

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

type CreateReq struct {
	Scope       string `json:"scope" src:"json" default:"vb" desc:"Scope"`
	Code        string `json:"code" src:"json" desc:"Role Code"`
	Name        string `json:"name" src:"json" desc:"Role Name"`
	Description *string `json:"description,omitempty" src:"json" desc:"Role Description"`
}

func create(x *vigo.X, req *CreateReq) (*models.Role, error) {
	// Check if role code already exists
	var count int64
	if err := cfg.DB().Model(&models.Role{}).Where("code = ?", req.Code).Count(&count).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}
	if count > 0 {
		return nil, vigo.ErrAlreadyExists.WithArgs("Role Code")
	}

	role := &models.Role{
		Code:     req.Code,
		Name:     req.Name,
		IsSystem: false, // Default to false for user created roles
		Status:   1,
	}
	if req.Description != nil {
		role.Description = *req.Description
	}

	if err := cfg.DB().Create(role).Error; err != nil {
		return nil, vigo.ErrDatabase.WithError(err)
	}

	return role, nil
}
