package mysqlrefertime

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) GetAll(ctx context.Context, status entity.ReferTimeStatus) ([]entity.ReferTime, error) {
	const op = "mysqlrefertime.GetAll"

	query := `SELECT * FROM refer_times where status = ?;`

	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyReferTimeGetAll, query)
	if err != nil {
		return nil, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

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

	referTimes := make([]entity.ReferTime, 0)
	for rows.Next() {
		referTime, err := scanReferTime(rows)
		if err != nil {
			return nil, richerror.New(op).WithErr(err).
				WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
		}

		referTimes = append(referTimes, referTime)
	}

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

	return referTimes, nil
}
