package keeper

import (
	"context"
	"errors"
	"strconv"

	"cosmos-test/x/cosmostest/types"

	sdk "github.com/cosmos/cosmos-sdk/types"
)

func (k msgServer) NewAuction(goCtx context.Context, msg *types.MsgNewAuction) (*types.MsgNewAuctionResponse, error) {
	ctx := sdk.UnwrapSDKContext(goCtx)

	next, found := k.Keeper.GetNextAuction(ctx)
	if !found {
		return nil, errors.New("Auction not found")
	}
	index := strconv.FormatUint(next.AuctionId, 10)

	auction := types.Auction{
		Index:       index,
		Name:        msg.Name,
		Description: msg.Description,
		Bids:        []*types.Bid{},
	}

	k.Keeper.SetAuction(ctx, auction)
	next.AuctionId++

	k.Keeper.SetNextAuction(ctx, types.NextAuction{next.AuctionId})

	return &types.MsgNewAuctionResponse{
		AuctionId: strconv.FormatUint(next.AuctionId, 10),
	}, nil
}
