package logic

import (
	"context"
	"fmt"

	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type CreateRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
	return &CreateRoleLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *CreateRoleLogic) CreateRole(in *system.RoleReq) (*system.CommonResp, error) {
	err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		role := sysModel.SundynixRole{Name: in.Name, Code: in.Code, Sort: int(in.Sort)}
		if err := tx.Create(&role).Error; err != nil {
			return fmt.Errorf("创建角色失败: %w", err)
		}
		for _, mid := range in.MenuIds {
			if err := tx.Create(&sysModel.SundynixRoleMenu{RoleID: role.ID, MenuID: mid}).Error; err != nil {
				return fmt.Errorf("关联菜单失败: %w", err)
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &system.CommonResp{Code: 200, Msg: "success"}, nil
}
