package biz

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

// Defining the `SMSLog` business logic.
type SMSLog struct {
	Trans     *util.Trans
	SMSLogDAL *dal.SMSLog
}

// 查询SMSLog列表
func (a *SMSLog) Query(ctx context.Context, params schema.SMSLogQueryParam) (*schema.SMSLogQueryResult, error) {
	params.Pagination = true

	result, err := a.SMSLogDAL.Query(ctx, params, schema.SMSLogQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// 获取单条SMSLog
func (a *SMSLog) Get(ctx context.Context, id uint) (*schema.SMSLog, error) {
	smsLog, err := a.SMSLogDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if smsLog == nil {
		return nil, errors.NotFound("", "SMSLog not found")
	}
	return smsLog, nil
}

// 创建SMSLog
func (a *SMSLog) Create(ctx context.Context, formItem *schema.SMSLogForm) (*schema.SMSLog, error) {
	smsLog := &schema.SMSLog{}

	if err := formItem.FillTo(smsLog); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.SMSLogDAL.Create(ctx, smsLog); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return smsLog, nil
}

// 修改SMSLog
func (a *SMSLog) Update(ctx context.Context, id uint, formItem *schema.SMSLogForm) error {
	smsLog, err := a.SMSLogDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if smsLog == nil {
		return errors.NotFound("", "SMSLog not found")
	}

	if err := formItem.FillTo(smsLog); err != nil {
		return err
	}
	smsLog.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.SMSLogDAL.Update(ctx, smsLog); err != nil {
			return err
		}
		return nil
	})
}

// 删除SMSLog
func (a *SMSLog) Delete(ctx context.Context, id uint) error {
	exists, err := a.SMSLogDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "SMSLog not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.SMSLogDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
