package database

import (
	"context"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"git.gocasts.ir/ebhomengo/niki/productapp/service/product"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)

type DB struct {
	conn *mysql.DB
}

func New(conn *mysql.DB) *DB {
	return &DB{
		conn: conn,
	}
}

func (db *DB) GetProducts(ctx context.Context, page, pageSize uint) ([]product.Product, error) {
	const Op = "domain.repository.mysql.order.get-shipping"

	query := "SELECT * FROM products ORDER BY id DESC limit ? offset ?"
	rows, err := db.conn.Conn().Query(query, page, pageSize)

	if rows.Err() != nil {
		return []product.Product{}, richerror.New(Op).WithErr(err)
	}

	defer rows.Close()

	var products []product.Product

	for rows.Next() {
		var s product.Product

		err := rows.Scan(
			&s.ID,
			&s.Name,
			&s.Slug,
			&s.Description,
			&s.Price,
			&s.Stock,
			&s.IsActive,
			&s.Features,
			&s.CreatedAt,
			&s.DeletedAt,
		)
		if err != nil {
			return nil, richerror.New(Op).WithErr(err)
		}

		products = append(products, s)
	}

	return products, nil
}
