package api

import (
	"context"
	"time"

	capi "git.vdhsn.com/barretthousen/barretthousen/src/catalog/api/grpc"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func NewCatalogServiceClient(conn grpc.ClientConnInterface) *CatalogServiceClient {
	return &CatalogServiceClient{
		CatalogClient: capi.NewCatalogClient(conn),
	}
}

type CatalogServiceClient struct {
	capi.CatalogClient
}

type Auction struct {
	Fingerprint    string    `json:"fingerprint,omitempty"`
	Title          string    `json:"title,omitempty"`
	Description    string    `json:"description,omitempty"`
	SourceSiteURL  string    `json:"source_site_url,omitempty"`
	SourceSiteName string    `json:"source_site_name,omitempty"`
	SourceURL      string    `json:"source_url,omitempty"`
	Country        string    `json:"country,omitempty"`
	Province       string    `json:"province,omitempty"`
	ItemCount      int       `json:"itemCount,omitempty"`
	Start          time.Time `json:"start,omitempty"`
	End            time.Time `json:"end,omitempty"`
}

type AuctionCreatedEvent struct {
	Fingerprint string
	ID          int
	Duplicate   bool
}

func (css *CatalogServiceClient) UpdateUpcomingAuction(ctx context.Context, a Auction) (AuctionCreatedEvent, error) {
	ac, err := css.ImportAuction(ctx, &capi.ImportAuctionMessage{
		Items:          int32(a.ItemCount),
		Start:          timestamppb.New(a.Start),
		End:            timestamppb.New(a.End),
		Title:          a.Title,
		Description:    a.Description,
		SourceSiteURL:  a.SourceSiteURL,
		SourceSiteName: a.SourceSiteName,
		SourceURL:      a.SourceURL,
		Country:        a.Country,
		Province:       a.Province,
	})
	if err != nil {
		return AuctionCreatedEvent{}, err
	}

	return AuctionCreatedEvent{
		Fingerprint: ac.Auction.Fingerprint,
		ID:          int(ac.Auction.Id),
		Duplicate:   ac.Duplicate,
	}, nil
}
