package dal

import (
	"context"

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

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

type SignIn struct {
	DB *gorm.DB
}

// Query notices from the database based on the provided parameters and options.
func (a *SignIn) Query(ctx context.Context, params schema.SignInQueryParam, opts ...schema.SignInQueryOptions) (*schema.SignInQueryResult, error) {
	var opt schema.SignInQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetSignInDB(ctx, a.DB)

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

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

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

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

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

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

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