package dal

import (
	"context"

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

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

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

// Query banners from the database based on the provided parameters and options.
func (a *Banner) Query(ctx context.Context, params schema.BannerQueryParam, opts ...schema.BannerQueryOptions) (*schema.BannerQueryResult, error) {
	var opt schema.BannerQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetBannerDB(ctx, a.DB)

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

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

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

	item := new(schema.Banner)
	ok, err := util.FindOne(ctx, GetBannerDB(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 banner exists in the database.
func (a *Banner) Exists(ctx context.Context, id uint) (bool, error) {
	ok, err := util.Exists(ctx, GetBannerDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

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

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

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