package benefactoraddressservice

import (
	"context"

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

func (s Service) Add(ctx context.Context, req param.BenefactorAddAddressRequest) (param.BenefactorAddAddressResponse, error) {
	const op = "benefactoraddressservice.Add"
	if fieldErrors, vErr := s.vld.ValidateAddAddress(ctx, req); vErr != nil {
		return param.BenefactorAddAddressResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}
	address, err := s.repo.CreateBenefactorAddress(ctx, entity.Address{
		PostalCode:   req.PostalCode,
		Address:      req.Address,
		Name:         req.Name,
		Lat:          req.Lat,
		Lon:          req.Lon,
		CityID:       req.CityID,
		BenefactorID: req.BenefactorID,
	})
	if err != nil {
		return param.BenefactorAddAddressResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}

	return param.BenefactorAddAddressResponse{Data: param.Data{
		ID:           address.ID,
		PostalCode:   address.PostalCode,
		Address:      address.Address,
		Name:         address.Name,
		Lat:          address.Lat,
		Lon:          address.Lon,
		CityID:       address.CityID,
		ProvinceID:   address.ProvinceID,
		BenefactorID: address.BenefactorID,
	}}, nil
}
