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) GetAddresses(ctx context.Context, benefactorID uint) ([]entity.Address, error) {
	const op = "mysqladdress.GetAddresses"

	query := `select * from addresses where benefactor_id = ? and deleted_at is null`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyAddressGetAllByBenefactorID, query)
	if err != nil {
		return nil, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	rows, err := stmt.QueryContext(ctx, benefactorID)
	if err != nil {
		return nil, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}
	defer rows.Close()

	addresses := make([]entity.Address, 0)

	for rows.Next() {
		address, sErr := scanAddress(rows)
		if sErr != nil {
			return nil, richerror.New(op).WithErr(sErr).
				WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
		}
		addresses = append(addresses, address)
	}

	if rErr := rows.Err(); rErr != nil {
		return nil, richerror.New(op).WithErr(rErr).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	return addresses, nil
}
