// 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/auth"
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
)

type CreateRequest struct {
	Name        string  `json:"name" src:"json" desc:"组织名称"`
	Code        string  `json:"code" src:"json" desc:"组织代码"`
	Description string  `json:"description,omitempty" src:"json" desc:"描述"`
	Logo        string  `json:"logo,omitempty" src:"json" desc:"Logo"`
	ParentID    *string `json:"parent_id,omitempty" src:"json" desc:"父组织ID"`
}

func create(x *vigo.X, req *CreateRequest) (*models.Org, error) {
	// 检查代码是否已存在
	var count int64
	cfg.DB().Model(&models.Org{}).Where("code = ?", req.Code).Count(&count)
	if count > 0 {
		return nil, vigo.ErrArgInvalid.WithString("organization code already exists")
	}

	// 获取当前用户ID作为所有者
	ownerID := getCurrentUserID(x)
	if ownerID == "" {
		return nil, vigo.ErrNotAuthorized
	}

	org := &models.Org{
		Name:        req.Name,
		Code:        req.Code,
		Description: req.Description,
		Logo:        req.Logo,
		OwnerID:     ownerID,
		ParentID:    req.ParentID,
		Status:      models.OrgStatusActive,
	}

	if err := cfg.DB().Create(org).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	// 授予创建者 admin 角色
	if err := auth.VBaseAuth.GrantRole(x.Context(), models.GrantRoleRequest{
		UserID:   ownerID,
		OrgID:    org.ID,
		RoleCode: "admin",
	}); err != nil {
		// 最好回滚，这里简化处理
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	return org, nil
}

func getCurrentUserID(x *vigo.X) string {
	if uid, ok := x.Get("user_id").(string); ok {
		return uid
	}
	return ""
}
