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 area storage instance
func GetAreaDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.Area))
}

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

// Query areas from the database based on the provided parameters and options.
func (a *Area) Query(ctx context.Context, params schema.AreaQueryParam, opts ...schema.AreaQueryOptions) (*schema.AreaQueryResult, error) {
	var opt schema.AreaQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetAreaDB(ctx, a.DB)

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

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

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

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

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

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

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