package dal

import (
	"context"

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

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

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

// Query points from the database based on the provided parameters and options.
func (a *Point) Query(ctx context.Context, params schema.PointQueryParam, opts ...schema.PointQueryOptions) (*schema.PointQueryResult, error) {
	var opt schema.PointQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetPointDB(ctx, a.DB)

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

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

// Get the specified point from the database.
func (a *Point) Get(ctx context.Context, id string, opts ...schema.PointQueryOptions) (*schema.Point, error) {
	var opt schema.PointQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

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

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

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

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