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 `Grade` business logic.
type Grade struct {
	Trans    *util.Trans
	GradeDAL *dal.Grade
}

// Query grades from the data access object based on the provided parameters and options.
func (a *Grade) Query(ctx context.Context, params schema.GradeQueryParam) (*schema.GradeQueryResult, error) {
	params.Pagination = true

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

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

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

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

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

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

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

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

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

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