package biz

import (
	"context"
	"time"

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

type House struct {
	Trans    *util.Trans
	HouseDAL *dal.House
}

func (a *House) Query(ctx context.Context, params schema.HouseQueryParam) (*schema.HouseQueryResult, error) {
	params.Pagination = true

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

func (a *House) Get(ctx context.Context, id uint) (*schema.House, error) {
	item, err := a.HouseDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if item == nil {
		return nil, errors.NotFound("", "house not found")
	}
	return item, nil
}

func (a *House) Create(ctx context.Context, formItem *schema.HouseForm) (*schema.House, error) {
	item := &schema.House{}

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

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

func (a *House) Update(ctx context.Context, id uint, formItem *schema.HouseForm) error {
	item, err := a.HouseDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if item == nil {
		return errors.NotFound("", "House not found")
	}

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

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

func (a *House) Delete(ctx context.Context, id uint) error {
	exists, err := a.HouseDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "HOUSE not found")
	}

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