package app_user

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

type updateOpts struct {
	AppID  string  `src:"path@app_id" desc:"应用ID"`
	UserID string  `src:"path@user_id" desc:"用户ID"`
	Status *string `json:"status" src:"json" desc:"状态"`
}

var _ = Router.Patch("/{user_id}", "更新应用用户", updateAppUser)

func updateAppUser(x *vigo.X, opts *updateOpts) (*models.AppUser, error) {
	appUser := &models.AppUser{}
	if err := cfg.DB().Where("app_id = ? AND user_id = ?", opts.AppID, opts.UserID).First(appUser).Error; err != nil {
		return nil, vigo.NewError("app_user not found").WithCode(404)
	}

	updates := map[string]interface{}{}
	if opts.Status != nil {
		updates["status"] = *opts.Status
	}

	if len(updates) > 0 {
		if err := cfg.DB().Model(appUser).Updates(updates).Error; err != nil {
			return nil, err
		}
	}

	return appUser, nil
}
