package biz

import (
	"context"
	"time"

	"github.guxuan/haibei/internal/mods/product/dal"
	"github.guxuan/haibei/internal/mods/product/schema"
	"github.guxuan/haibei/pkg/errors"
	"github.guxuan/haibei/pkg/util"
)

// Defining the `ProductCategory` business logic.
type ProductCategory struct {
	Trans              *util.Trans
	ProductCategoryDAL *dal.ProductCategory
}

// Query product categories from the data access object based on the provided parameters and options.
func (a *ProductCategory) Query(ctx context.Context, params schema.ProductCategoryQueryParam) (*schema.ProductCategoryQueryResult, error) {
	params.Pagination = true

	result, err := a.ProductCategoryDAL.Query(ctx, params, schema.ProductCategoryQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified product category from the data access object.
func (a *ProductCategory) Get(ctx context.Context, id uint) (*schema.ProductCategory, error) {
	productCategory, err := a.ProductCategoryDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if productCategory == nil {
		return nil, errors.NotFound("", "Product category not found")
	}
	return productCategory, nil
}

// Create a new product category in the data access object.
func (a *ProductCategory) Create(ctx context.Context, formItem *schema.ProductCategoryForm) (*schema.ProductCategory, error) {
	productCategory := &schema.ProductCategory{}

	if err := formItem.FillTo(productCategory); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.ProductCategoryDAL.Create(ctx, productCategory); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return productCategory, nil
}

// Update the specified product category in the data access object.
func (a *ProductCategory) Update(ctx context.Context, id uint, formItem *schema.ProductCategoryForm) error {
	productCategory, err := a.ProductCategoryDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if productCategory == nil {
		return errors.NotFound("", "Product category not found")
	}

	if err := formItem.FillTo(productCategory); err != nil {
		return err
	}
	productCategory.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.ProductCategoryDAL.Update(ctx, productCategory); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified product category from the data access object.
func (a *ProductCategory) Delete(ctx context.Context, id uint) error {
	exists, err := a.ProductCategoryDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Product category not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.ProductCategoryDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
