package dal

import (
	"context"

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

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

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

// Query activities from the database based on the provided parameters and options.
func (a *Activity) Query(ctx context.Context, params schema.ActivityQueryParam, opts ...schema.ActivityQueryOptions) (*schema.ActivityQueryResult, error) {
	var opt schema.ActivityQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetActivityDB(ctx, a.DB)

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

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

// Get the specified activity from the database.
func (a *Activity) Get(ctx context.Context, id uint, opts ...schema.ActivityQueryOptions) (*schema.Activity, error) {
	var opt schema.ActivityQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	item := new(schema.Activity)
	ok, err := util.FindOne(ctx, GetActivityDB(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
}

// Exists checks if the specified activity exists in the database.
func (a *Activity) Exists(ctx context.Context, id uint) (bool, error) {
	ok, err := util.Exists(ctx, GetActivityDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

// Create a new activity.
func (a *Activity) Create(ctx context.Context, item *schema.Activity) error {
	result := GetActivityDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

// Update the specified activity in the database.
func (a *Activity) Update(ctx context.Context, item *schema.Activity) error {
	result := GetActivityDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
	return errors.WithStack(result.Error)
}

// Delete the specified activity from the database.
func (a *Activity) Delete(ctx context.Context, id uint) error {
	result := GetActivityDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Activity))
	return errors.WithStack(result.Error)
}
