package steps

// |@@| F

import (
	"context"
	"gardening/src/dat/maes"
	"gardening/src/lib/error"
	"gardening/src/lib/maestro"
	"gardening/src/srv/fetchers"
	"gardening/src/srv/handlers"
	"gardening/src/srv/molders"
)

type SaveEntityStep struct {
	Maestro              *maestro.Maestro
	UpdateUserFormMolder *molders.UpdateUserFormMolder
	UserFetcher          *fetchers.UserFetcher
	UserHandler          *handlers.UserHandler
}

func (this *SaveEntityStep) Act(ctx context.Context, in *maes.UpdateUserMaeIn, out *maes.UpdateUserMaeOut) (bool, error) {
	var err error
	entity, has, err := this.UserFetcher.FindOneById(ctx, in.Request.Form.Id, nil)
	if err != nil {
		return false, err
	}
	if !has {
		return false, erro.N("No entity found")
	}
	entity, fields := this.UpdateUserFormMolder.ToEntity(&in.Request.Form, entity)
	out.Response.User, err = this.UserHandler.UpdateFields(ctx, entity, fields, nil)
	if err != nil {
		return false, err
	}
	this.Maestro.AddSuccessMessage(&out.Extra, "User updated")
	return true, nil
}
