package mysqladdress

import (
	"context"

	"git.gocasts.ir/ebhomengo/niki/entity"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)

func (d *DB) UpdateAddress(ctx context.Context, address entity.Address) error {
	const op = "mysqladdress.UpdateAddress"

	provinceID, err := d.getProvinceIDByCityID(ctx, address.CityID)
	if err != nil {
		return err
	}

	query := `UPDATE addresses 
			  SET postal_code = ?, address = ?, lat = ?, lon = ?, name = ?, city_id = ?, province_id = ? 
			  WHERE id = ? AND benefactor_id = ? AND deleted_at IS NULL`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyAddressUpdate, query)
	if err != nil {
		return richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	_, uErr := stmt.ExecContext(ctx, address.PostalCode, address.Address, address.Lat, address.Lon, address.Name, address.CityID, provinceID, address.ID, address.BenefactorID)
	if err != nil {
		return richerror.New(op).WithErr(uErr).WithMessage(errmsg.ErrorMsgCantUpdateRecord).
			WithKind(richerror.KindUnexpected)
	}

	return nil
}
