package mysqlbenefactor

import (
	"context"

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

func (d *DB) GetAllBenefactor(ctx context.Context, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest, searchParams *param.QuerySearch) ([]entity.Benefactor, uint, error) {
	const op = "mysqlbenefactor.GetAllBenefactor"
	var sArgs []any
	table := "benefactors"
	joinQuery := ""
	baseQuery := `SELECT * FROM benefactors`

	if searchParams != nil {
		baseQuery, sArgs = builder.BuildGetSearchQuery(baseQuery, joinQuery, *searchParams)
	}
	query, fArgs := builder.BuildGetAllQuery(baseQuery, table, filter, pagination, sort)
	args := append(sArgs, fArgs...)

	rows, qErr := d.conn.Conn().QueryContext(ctx, query, args...)
	if qErr != nil {
		return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	defer rows.Close()

	benefactors := make([]entity.Benefactor, 0)
	for rows.Next() {
		benefactor, sErr := scanBenefactor(rows)
		if sErr != nil {
			return nil, 0, richerror.New(op).WithErr(sErr).
				WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
		}
		benefactors = append(benefactors, benefactor)
	}

	if rErr := rows.Err(); rErr != nil {
		return nil, 0, richerror.New(op).WithErr(rErr).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}
	var total uint
	query, args = builder.BuildGetTotalQuery(table, joinQuery, filter, searchParams, false)
	qErr = d.conn.Conn().QueryRowContext(ctx, query, args...).Scan(&total)
	if qErr != nil {
		return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	return benefactors, total, nil
}
