package biz

import (
	"context"
	"time"

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

// Defining the `Point` business logic.
type Point struct {
	Trans    *util.Trans
	PointDAL *dal.Point
}

// Query points from the data access object based on the provided parameters and options.
func (a *Point) Query(ctx context.Context, params schema.PointQueryParam) (*schema.PointQueryResult, error) {
	params.Pagination = true

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

// Get the specified point from the data access object.
func (a *Point) Get(ctx context.Context, id string) (*schema.Point, error) {
	point, err := a.PointDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if point == nil {
		return nil, errors.NotFound("", "Point not found")
	}
	return point, nil
}

// Create a new point in the data access object.
func (a *Point) Create(ctx context.Context, formItem *schema.PointForm) (*schema.Point, error) {
	point := &schema.Point{
		ID:        util.NewXID(),
		CreatedAt: time.Now(),
	}

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

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

// Update the specified point in the data access object.
func (a *Point) Update(ctx context.Context, id string, formItem *schema.PointForm) error {
	point, err := a.PointDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if point == nil {
		return errors.NotFound("", "Point not found")
	}

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

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

// Delete the specified point from the data access object.
func (a *Point) Delete(ctx context.Context, id string) error {
	exists, err := a.PointDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Point not found")
	}

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