package benefactoraddressservice

import (
	"context"

	param "git.gocasts.ir/ebhomengo/niki/param/benefactor/address"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

func (s Service) Update(ctx context.Context, req param.UpdateAddressRequest) (param.UpdateAddressResponse, error) {
	const op = "benefactoraddressservice.Update"
	if fieldErrors, vErr := s.vld.ValidateUpdateAddress(ctx, req); vErr != nil {
		return param.UpdateAddressResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}
	address, gErr := s.repo.GetAddressByID(ctx, req.ID)
	if gErr != nil {
		return param.UpdateAddressResponse{}, richerror.New(op).WithErr(gErr)
	}

	address.ID = req.ID
	address.PostalCode = req.PostalCode
	address.Address = req.Address
	address.Name = req.Name
	address.Lat = req.Lat
	address.Lon = req.Lon
	address.CityID = req.CityID
	address.BenefactorID = req.BenefactorID

	uErr := s.repo.UpdateAddress(ctx, address)
	if uErr != nil {
		return param.UpdateAddressResponse{}, richerror.New(op).WithErr(uErr)
	}

	return param.UpdateAddressResponse{}, nil
}
