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 GetHouseDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.House))
}

type House struct {
	DB *gorm.DB
}

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

	db := GetHouseDB(ctx, a.DB)

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

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

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

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

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

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

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