package mysqlbenefactor

import (
	"context"
	"fmt"

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

func (d *DB) GetByIDs(ctx context.Context, benefactorIDs []any) (map[uint]entity.Benefactor, error) {
	const op = "mysqlbenefactor.GetByIDs"

	if len(benefactorIDs) <= 0 {
		return nil, nil
	}
	query := `select * from benefactors where id in (%s)`
	param := "?"
	for i := 1; i < len(benefactorIDs); i++ {
		param += ",?"
	}
	query = fmt.Sprintf(query, param)
	rows, qErr := d.conn.Conn().QueryContext(ctx, query, benefactorIDs...)
	if qErr != nil {
		return nil, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	defer rows.Close()

	benefactors := make(map[uint]entity.Benefactor)
	for rows.Next() {
		benefactor, sErr := scanBenefactor(rows)
		if sErr != nil {
			return nil, richerror.New(op).WithErr(sErr).
				WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
		}
		benefactors[benefactor.ID] = benefactor
	}
	if rErr := rows.Err(); rErr != nil {
		return nil, richerror.New(op).WithErr(rErr).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}
	return benefactors, nil
}
