package biz

import (
	"context"
	"time"

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

// Defining the `Banner` business logic.
type Banner struct {
	Trans     *util.Trans
	BannerDAL *dal.Banner
}

// Query banners from the data access object based on the provided parameters and options.
func (a *Banner) Query(ctx context.Context, params schema.BannerQueryParam) (*schema.BannerQueryResult, error) {
	params.Pagination = true

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

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

// Create a new banner in the data access object.
func (a *Banner) Create(ctx context.Context, formItem *schema.BannerForm) (*schema.Banner, error) {
	banner := &schema.Banner{}

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

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

// Update the specified banner in the data access object.
func (a *Banner) Update(ctx context.Context, id uint, formItem *schema.BannerForm) error {
	banner, err := a.BannerDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if banner == nil {
		return errors.NotFound("", "Banner not found")
	}

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

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

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

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