package dal

import (
	"context"
	"github.guxuan/haibei/internal/mods/common/schema"
	"github.guxuan/haibei/pkg/errors"
	"github.guxuan/haibei/pkg/util"
	"gorm.io/gorm"
)

// Get smsLog storage instance
func GetSMSLogDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.SMSLog))
}

// Defining the `SMSLog` data access object.
type SMSLog struct {
	DB *gorm.DB
}

// 查询SMSLog列表
func (a *SMSLog) Query(ctx context.Context, params schema.SMSLogQueryParam, opts ...schema.SMSLogQueryOptions) (*schema.SMSLogQueryResult, error) {
	var opt schema.SMSLogQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetSMSLogDB(ctx, a.DB)

	var list schema.SMSLogs
	pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	queryResult := &schema.SMSLogQueryResult{
		PageResult: pageResult,
		Data:       list,
	}
	return queryResult, nil
}

// 获取单条SMSLog
func (a *SMSLog) Get(ctx context.Context, id uint, opts ...schema.SMSLogQueryOptions) (*schema.SMSLog, error) {
	var opt schema.SMSLogQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	item := new(schema.SMSLog)
	ok, err := util.FindOne(ctx, GetSMSLogDB(ctx, a.DB).Where("id=?", id), opt.QueryOptions, item)
	if err != nil {
		return nil, errors.WithStack(err)
	} else if !ok {
		return nil, nil
	}
	return item, nil
}

// 检查是否存在
func (a *SMSLog) Exists(ctx context.Context, id uint) (bool, error) {
	ok, err := util.Exists(ctx, GetSMSLogDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

// 创建SMSLog
func (a *SMSLog) Create(ctx context.Context, item *schema.SMSLog) error {
	result := GetSMSLogDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

// 修改SMSLog
func (a *SMSLog) Update(ctx context.Context, item *schema.SMSLog) error {
	result := GetSMSLogDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
	return errors.WithStack(result.Error)
}

// 删除SMSLog
func (a *SMSLog) Delete(ctx context.Context, id uint) error {
	result := GetSMSLogDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.SMSLog))
	return errors.WithStack(result.Error)
}
