package system

import (
	"context"
	"errors"

	"kra/internal/biz/system"
	"kra/internal/data/model"

	"gorm.io/gorm"
)

type authorityBtnRepo struct {
	db *gorm.DB
}

// NewAuthorityBtnRepo 创建角色按钮权限仓储
func NewAuthorityBtnRepo(db *gorm.DB) system.AuthorityBtnRepo {
	return &authorityBtnRepo{db: db}
}

func (r *authorityBtnRepo) GetAuthorityBtn(ctx context.Context, authorityId, menuId uint) ([]uint, error) {
	var btns []model.SysAuthorityBtn
	if err := r.db.WithContext(ctx).
		Where("authority_id = ? AND sys_menu_id = ?", authorityId, menuId).
		Find(&btns).Error; err != nil {
		return nil, err
	}
	selected := make([]uint, len(btns))
	for i, b := range btns {
		selected[i] = uint(b.SysBaseMenuBtnID)
	}
	return selected, nil
}

func (r *authorityBtnRepo) SetAuthorityBtn(ctx context.Context, authorityId, menuId uint, btnIds []uint) error {
	return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		// 删除旧权限
		if err := tx.Where("authority_id = ? AND sys_menu_id = ?", authorityId, menuId).
			Delete(&model.SysAuthorityBtn{}).Error; err != nil {
			return err
		}
		// 创建新权限
		if len(btnIds) > 0 {
			btns := make([]model.SysAuthorityBtn, len(btnIds))
			for i, btnId := range btnIds {
				btns[i] = model.SysAuthorityBtn{
					AuthorityID:      int64(authorityId),
					SysMenuID:        int64(menuId),
					SysBaseMenuBtnID: int64(btnId),
				}
			}
			if err := tx.Create(&btns).Error; err != nil {
				return err
			}
		}
		return nil
	})
}

func (r *authorityBtnRepo) CanRemoveAuthorityBtn(ctx context.Context, btnId uint) error {
	var count int64
	if err := r.db.WithContext(ctx).Model(&model.SysAuthorityBtn{}).
		Where("sys_base_menu_btn_id = ?", btnId).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("此按钮正在被使用无法删除")
	}
	return nil
}
