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 HouseArticle struct {
	Trans           *util.Trans
	HouseArticleDAL *dal.HouseArticle
}

func (a *HouseArticle) Query(ctx context.Context, params schema.HouseArticleQueryParam) (*schema.HouseArticleQueryResult, error) {
	params.Pagination = true

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

func (a *HouseArticle) Get(ctx context.Context, id uint) (*schema.HouseArticle, error) {
	item, err := a.HouseArticleDAL.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 *HouseArticle) Create(ctx context.Context, formItem *schema.HouseArticleForm) (*schema.HouseArticle, error) {
	item := &schema.HouseArticle{}

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

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

func (a *HouseArticle) Update(ctx context.Context, id uint, formItem *schema.HouseArticleForm) error {
	item, err := a.HouseArticleDAL.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.HouseArticleDAL.Update(ctx, item); err != nil {
			return err
		}
		return nil
	})
}

func (a *HouseArticle) Delete(ctx context.Context, id uint) error {
	exists, err := a.HouseArticleDAL.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.HouseArticleDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
