package dal

import (
	"context"

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

// Get product category storage instance
func GetProductCategoryDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.ProductCategory))
}

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

// Query product categories from the database based on the provided parameters and options.
func (a *ProductCategory) Query(ctx context.Context, params schema.ProductCategoryQueryParam, opts ...schema.ProductCategoryQueryOptions) (*schema.ProductCategoryQueryResult, error) {
	var opt schema.ProductCategoryQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetProductCategoryDB(ctx, a.DB)

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

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

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

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

// Create a new product category.
func (a *ProductCategory) Create(ctx context.Context, item *schema.ProductCategory) error {
	result := GetProductCategoryDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

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

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