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 AssignRoleMenusLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

// AssignRoleMenus 给角色授权菜单（全量替换）
func (l *AssignRoleMenusLogic) AssignRoleMenus(in *system.AssignRoleMenusReq) (*system.CommonResp, error) {
	err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		// 先清除旧的菜单关联
		if err := tx.Where("role_id = ?", in.RoleId).Delete(&sysModel.SundynixRoleMenu{}).Error; err != nil {
			return fmt.Errorf("清除菜单关联失败: %w", err)
		}
		// 重新批量写入
		for _, mid := range in.MenuIds {
			if err := tx.Create(&sysModel.SundynixRoleMenu{RoleID: in.RoleId, 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
}
