//
// get.go
// Copyright (C) 2025 veypi <i@veypi.com>
// 2025-05-06 15:21
// Distributed under terms of the MIT license.
//

package role

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

	"github.com/veypi/vigo"
)

type getIDReq struct {
	ID string `src:"path@id" desc:"记录ID"`
}

var _ = Router.Get("/{id}", "获取用户角色详情", userRoleGet)

func userRoleGet(x *vigo.X, req *getIDReq) (*models.UserRole, error) {
	data := &models.UserRole{}
	err := cfg.DB().Where("id = ?", req.ID).First(data).Error
	return data, err
}

type listOpts struct {
	UserID *string `json:"user_id"  src:"path@user_id" desc:"用户ID"`
	RoleID *string `json:"role_id"  src:"query" desc:"角色ID"`
	AppID  *string `json:"app_id"  src:"query" desc:"应用ID"`
	Status *string `json:"status"  src:"query" desc:"状态"`
}

var _ = Router.Get("/", "获取用户角色列表", userRoleList)

type userRoleListItem struct {
	models.UserRole
	Username string `json:"username"`
	Nickname string `json:"nickname"`
	Icon     string `json:"icon"`
	RoleName string `json:"role_name"`
}

func userRoleList(x *vigo.X, opts *listOpts) ([]*userRoleListItem, error) {
	data := make([]*userRoleListItem, 0, 10)
	// data := make([]*M.UserRole, 0, 10)

	query := cfg.DB().Debug().Table("user_roles").Select("user_roles.*,users.username,users.nickname,users.icon,roles.name as role_name").
		Joins("JOIN users ON users.id = user_roles.user_id").
		Joins("JOIN roles ON roles.id = user_roles.role_id")
	if opts.UserID != nil && *opts.UserID != "-" {
		query = query.Where("user_id LIKE ?", opts.UserID)
	}
	if opts.RoleID != nil {
		query = query.Where("role_id LIKE ?", opts.RoleID)
	}
	if opts.AppID != nil {
		query = query.Where("app_id LIKE ?", opts.AppID)
	}
	if opts.Status != nil {
		query = query.Where("status LIKE ?", opts.Status)
	}
	err := query.Scan(&data).Error

	return data, err
}
