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

// Query areas from the data access object based on the provided parameters and options.
func (a *Area) Query(ctx context.Context, params schema.AreaQueryParam) (*schema.AreaQueryResult, error) {
	params.Pagination = true

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

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

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

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

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

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

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

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

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

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