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

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

// Query companies from the database based on the provided parameters and options.
func (a *ReceptionCenter) Query(ctx context.Context, params schema.ReceptionCenterQueryParam, opts ...schema.ReceptionCenterQueryOptions) (*schema.ReceptionCenterQueryResult, error) {
	var opt schema.ReceptionCenterQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetReceptionCenterDB(ctx, a.DB)

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

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

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

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

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

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

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