package model

import (
	"context"
	"gorm.io/gorm"
	"yx-dataset-server/app/errors"
	"yx-dataset-server/app/model/entity"
	"yx-dataset-server/app/schema"
)

// NewUserRole 创建UserRole存储实例
func NewUserRole(db *gorm.DB) *UserRole {
	return &UserRole{db}
}

// UserRole UserRole存储
type UserRole struct {
	db *gorm.DB
}

func (a *UserRole) getQueryOption(opts ...schema.UserRoleQueryOptions) schema.UserRoleQueryOptions {
	var opt schema.UserRoleQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}
	return opt
}

// Query 查询数据
func (a *UserRole) Query(ctx context.Context, params schema.UserRoleQueryParam, opts ...schema.UserRoleQueryOptions) (*schema.UserRoleQueryResult, error) {
	db := entity.GetUserRoleDB(ctx, a.db)

	if v := params.UserId; v != "" {
		db = db.Where("user_id = ?", v)
	}
	if v := params.RoleId; v != "" {
		db = db.Where("role_id = ?", v)
	}

	db = db.Order("id DESC")

	opt := a.getQueryOption(opts...)
	var list entity.UserRoles
	pr, err := WrapPageQuery(ctx, db, opt.PageParam, &list)
	if err != nil {
		return nil, errors.ErrDBServerInternalError
	}
	qr := &schema.UserRoleQueryResult{
		PageResult: pr,
		Data:       list.ToSchemaUserRoles(),
	}

	return qr, nil
}

// Get 查询指定数据
func (a *UserRole) Get(ctx context.Context, recordID string, opts ...schema.UserRoleQueryOptions) (*schema.UserRole, error) {
	db := entity.GetUserRoleDB(ctx, a.db).Where("record_id=?", recordID)
	var item entity.UserRole
	ok, err := FindOne(ctx, db, &item)
	if err != nil {
		return nil, errors.ErrDBServerInternalError
	} else if !ok {
		return nil, nil
	}

	return item.ToSchemaUserRole(), nil
}

// Create 创建数据
func (a *UserRole) Create(ctx context.Context, item schema.UserRole) error {
	UserRole := entity.SchemaUserRole(item).ToUserRole()
	result := entity.GetUserRoleDB(ctx, a.db).Create(UserRole)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// Update 更新数据
func (a *UserRole) Update(ctx context.Context, recordID string, item schema.UserRole) error {
	UserRole := entity.SchemaUserRole(item).ToUserRole()
	result := entity.GetUserRoleDB(ctx, a.db).Where("record_id=?", recordID).Omit("record_id", "creator").Updates(UserRole)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// Delete 删除数据
func (a *UserRole) Delete(ctx context.Context, recordID string) error {
	result := entity.GetUserRoleDB(ctx, a.db).Where("record_id=?", recordID).Delete(entity.UserRole{})
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// UpdateStatus 更新状态
func (a *UserRole) UpdateStatus(ctx context.Context, recordID string, status int) error {
	result := entity.GetUserRoleDB(ctx, a.db).Where("record_id=?", recordID).Update("status", status)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}
