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 `ActivityDetail` business logic.
type ActivityDetail struct {
	Trans             *util.Trans
	ActivityDetailDAL *dal.ActivityDetail
}

// Query activity details from the data access object based on the provided parameters and options.
func (a *ActivityDetail) Query(ctx context.Context, params schema.ActivityDetailQueryParam) (*schema.ActivityDetailQueryResult, error) {
	params.Pagination = true

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

// Get the specified activity detail from the data access object.
func (a *ActivityDetail) Get(ctx context.Context, id uint) (*schema.ActivityDetail, error) {
	activityDetail, err := a.ActivityDetailDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if activityDetail == nil {
		return nil, errors.NotFound("", "Activity detail not found")
	}
	return activityDetail, nil
}

// Create a new activity detail in the data access object.
func (a *ActivityDetail) Create(ctx context.Context, formItem *schema.ActivityDetailForm) (*schema.ActivityDetail, error) {
	activityDetail := &schema.ActivityDetail{}

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

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

// Update the specified activity detail in the data access object.
func (a *ActivityDetail) Update(ctx context.Context, id uint, formItem *schema.ActivityDetailForm) error {
	activityDetail, err := a.ActivityDetailDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if activityDetail == nil {
		return errors.NotFound("", "Activity detail not found")
	}

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

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

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

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