// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.

package org

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

type ListMembersRequest struct {
	OrgID    string `src:"path@org_id" desc:"组织ID"`
	Page     int    `json:"page" src:"query" default:"1"`
	PageSize int    `json:"page_size" src:"query" default:"20"`
}

type MemberInfo struct {
	models.OrgMember
	Username string `json:"username"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
	Email    string `json:"email"`
}

type ListMembersResponse struct {
	Items      []MemberInfo `json:"items"`
	Total      int64        `json:"total"`
	Page       int          `json:"page"`
	PageSize   int          `json:"page_size"`
	TotalPages int          `json:"total_pages"`
}

func listMembers(x *vigo.X, req *ListMembersRequest) (*ListMembersResponse, error) {
	db := cfg.DB().Model(&models.OrgMember{}).Where("org_id = ?", req.OrgID)

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

	var members []models.OrgMember
	offset := (req.Page - 1) * req.PageSize
	if err := db.Order("created_at DESC").Offset(offset).Limit(req.PageSize).Find(&members).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	// 获取用户信息
	var result []MemberInfo
	for _, m := range members {
		var user models.User
		cfg.DB().First(&user, "id = ?", m.UserID)
		result = append(result, MemberInfo{
			OrgMember: m,
			Username:  user.Username,
			Nickname:  user.Nickname,
			Avatar:    user.Avatar,
			Email:     user.Email,
		})
	}

	totalPages := int(total) / req.PageSize
	if int(total)%req.PageSize > 0 {
		totalPages++
	}

	return &ListMembersResponse{
		Items:      result,
		Total:      total,
		Page:       req.Page,
		PageSize:   req.PageSize,
		TotalPages: totalPages,
	}, nil
}
