package biz

import (
	"context"
	"time"

	"github.guxuan/haibei/internal/mods/activity/dal"
	"github.guxuan/haibei/internal/mods/activity/schema"
	"github.guxuan/haibei/pkg/errors"
	"github.guxuan/haibei/pkg/util"
)

// Defining the `QeustionDetail` business logic.
type QeustionDetail struct {
	Trans             *util.Trans
	QeustionDetailDAL *dal.QeustionDetail
}

// Query qeustion details from the data access object based on the provided parameters and options.
func (a *QeustionDetail) Query(ctx context.Context, params schema.QeustionDetailQueryParam) (*schema.QeustionDetailQueryResult, error) {
	params.Pagination = true

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

// Get the specified qeustion detail from the data access object.
func (a *QeustionDetail) Get(ctx context.Context, id uint) (*schema.QeustionDetail, error) {
	qeustionDetail, err := a.QeustionDetailDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if qeustionDetail == nil {
		return nil, errors.NotFound("", "Qeustion detail not found")
	}
	return qeustionDetail, nil
}

// Create a new qeustion detail in the data access object.
func (a *QeustionDetail) Create(ctx context.Context, formItem *schema.QeustionDetailForm) (*schema.QeustionDetail, error) {
	qeustionDetail := &schema.QeustionDetail{}

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

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

// Update the specified qeustion detail in the data access object.
func (a *QeustionDetail) Update(ctx context.Context, id uint, formItem *schema.QeustionDetailForm) error {
	qeustionDetail, err := a.QeustionDetailDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if qeustionDetail == nil {
		return errors.NotFound("", "Qeustion detail not found")
	}

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

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

// Delete the specified qeustion detail from the data access object.
func (a *QeustionDetail) Delete(ctx context.Context, id uint) error {
	exists, err := a.QeustionDetailDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Qeustion detail not found")
	}

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