package mysqlkindbox

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) GetAllKindBox(ctx context.Context, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest, searchParams *param.QuerySearch) ([]entity.KindBox, uint, error) {
	const op = "mysqlkindbox.GetAllKindBox"
	var sArgs []any
	table := "kind_boxes"
	joinQuery := " INNER JOIN benefactors ON benefactor_id = benefactors.id WHERE (%s) "
	baseQuery := `SELECT kind_boxes.* FROM kind_boxes`

	if searchParams != nil {
		baseQuery, sArgs = builder.BuildGetSearchQuery(baseQuery, joinQuery, *searchParams)
	}
	filterQuery, fArgs := builder.BuildGetAllQuery(baseQuery, table, filter, pagination, sort)
	query := builder.BuildDeletedAtQuery(filterQuery, table)
	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()
	kindBoxes := make([]entity.KindBox, 0)
	for rows.Next() {
		kindBox, sErr := scanKindBox(rows)
		if sErr != nil {
			return nil, 0, richerror.New(op).WithErr(sErr).
				WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
		}
		kindBoxes = append(kindBoxes, kindBox)
	}

	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, true)
	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 kindBoxes, total, nil
}
