package dal

import (
	"context"

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

func GetHouseArticleDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.HouseArticle))
}

type HouseArticle struct {
	DB *gorm.DB
}

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

	db := GetHouseArticleDB(ctx, a.DB)

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

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

func (a *HouseArticle) Get(ctx context.Context, id uint, opts ...schema.HouseArticleQueryOptions) (*schema.HouseArticle, error) {
	var opt schema.HouseArticleQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

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

func (a *HouseArticle) Exists(ctx context.Context, id uint) (bool, error) {
	ok, err := util.Exists(ctx, GetHouseArticleDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

func (a *HouseArticle) Create(ctx context.Context, item *schema.HouseArticle) error {
	result := GetHouseArticleDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

func (a *HouseArticle) Update(ctx context.Context, item *schema.HouseArticle) error {
	result := GetHouseArticleDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
	return errors.WithStack(result.Error)
}

func (a *HouseArticle) Delete(ctx context.Context, id uint) error {
	result := GetHouseArticleDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.HouseArticle))
	return errors.WithStack(result.Error)
}
