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 GetCompanyDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.Company))
}

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

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

	db := GetCompanyDB(ctx, a.DB)

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

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

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

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

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

// Update the specified company in the database.
func (a *Company) Update(ctx context.Context, item *schema.Company) error {
	result := GetCompanyDB(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 *Company) Delete(ctx context.Context, id uint) error {
	result := GetCompanyDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Company))
	return errors.WithStack(result.Error)
}
