package app_user

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

type listOpts struct {
	AppID    string `src:"path@app_id" desc:"应用ID"`
	Page     int    `src:"query" desc:"页码" default:"1"`
	PageSize int    `src:"query" desc:"每页数量" default:"20"`
	Status   string `src:"query" desc:"状态" default:""`
}

type listResponse struct {
	Total int64             `json:"total"`
	Items []*models.AppUser `json:"items"`
}

var _ = Router.Get("/", "获取应用用户列表", listAppUsers)

func listAppUsers(x *vigo.X, opts *listOpts) (*listResponse, error) {
	query := cfg.DB().Model(&models.AppUser{}).Where("app_id = ?", opts.AppID)

	if opts.Status != "" {
		query = query.Where("status = ?", opts.Status)
	}

	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize)

	var users []*models.AppUser
	if err := query.Find(&users).Error; err != nil {
		return nil, err
	}

	return &listResponse{
		Total: total,
		Items: users,
	}, nil
}
