package mysqlrefertime

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, referTimeIDs []any) (map[uint]entity.ReferTime, error) {
	const op = "mysqlrefertime.GetByIDs"

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

	defer rows.Close()

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