package biz

import (
	"context"
	"time"

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

// Defining the `ProductOrder` business logic.
type ProductOrder struct {
	Trans           *util.Trans
	ProductOrderDAL *dal.ProductOrder
}

// Query product orders from the data access object based on the provided parameters and options.
func (a *ProductOrder) Query(ctx context.Context, params schema.ProductOrderQueryParam) (*schema.ProductOrderQueryResult, error) {
	params.Pagination = true

	result, err := a.ProductOrderDAL.Query(ctx, params, schema.ProductOrderQueryOptions{
		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 order from the data access object.
func (a *ProductOrder) Get(ctx context.Context, id uint) (*schema.ProductOrder, error) {
	productOrder, err := a.ProductOrderDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if productOrder == nil {
		return nil, errors.NotFound("", "Product order not found")
	}
	return productOrder, nil
}

// Create a new product order in the data access object.
func (a *ProductOrder) Create(ctx context.Context, formItem *schema.ProductOrderForm) (*schema.ProductOrder, error) {
	productOrder := &schema.ProductOrder{}

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

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

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

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

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

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

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