package dal

import (
	"context"

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

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

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

// Query apps from the database based on the provided parameters and options.
func (a *App) Query(ctx context.Context, params schema.AppQueryParam, opts ...schema.AppQueryOptions) (*schema.AppQueryResult, error) {
	var opt schema.AppQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetAppDB(ctx, a.DB)

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

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

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

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

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

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

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