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

// Query activities from the data access object based on the provided parameters and options.
func (a *Activity) Query(ctx context.Context, params schema.ActivityQueryParam) (*schema.ActivityQueryResult, error) {
	params.Pagination = true

	result, err := a.ActivityDAL.Query(ctx, params, schema.ActivityQueryOptions{
		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 from the data access object.
func (a *Activity) Get(ctx context.Context, id uint) (*schema.Activity, error) {
	activity, err := a.ActivityDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if activity == nil {
		return nil, errors.NotFound("", "Activity not found")
	}
	return activity, nil
}

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

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

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

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

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

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

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

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