package marketplace

import (
	"encoding/json"
	"sipro-mps/pkg/utils"

	"github.com/go-faster/errors"
)

const (
	WildberriesBaseMarketplace = 0
	OzonBaseMarketplace        = 1
	YandexBaseMarketplace      = 2
)

type Marketplace struct {
	ID              int    `json:"id"`
	BaseMarketplace int    `json:"base_marketplace"`
	AuthData        string `json:"auth_data"`
	WarehouseID     string `json:"warehouse_id"`
	AuthDataJson    []byte `json:"auth_data_json,omitempty"`
	CampaignID      string `json:"campaign_id,omitempty"`
}

func (m *Marketplace) getIdentifierWildberries() (string, error) {
	_, claims, err := utils.DecodeWildberriesJwt(m.AuthDataJson)
	if err != nil {
		return "", err
	}
	sellerId := claims["sid"].(string)
	return sellerId, err
}

func (m *Marketplace) getIdentifierOzon() (string, error) {
	if m.AuthDataJson == nil {
		return "", nil
	}
	var authData map[string]interface{}
	if err := json.Unmarshal(m.AuthDataJson, &authData); err != nil {
		return "", errors.Wrap(err, "unmarshal AuthDataJson")
	}
	if identifier, ok := authData["clientId"].(string); ok {
		return identifier, nil
	}
	return "", errors.New("identifier not found in AuthDataJson")
}

func (m *Marketplace) GetIdentifier() (string, error) {
	switch m.BaseMarketplace {
	case WildberriesBaseMarketplace:
		return m.getIdentifierWildberries()
	case OzonBaseMarketplace:
		return m.getIdentifierOzon()
	case YandexBaseMarketplace:
		return "", errors.New("Yandex marketplace does not support identifier retrieval")
	default:
		return "", errors.Errorf("unknown base marketplace: %d", m.BaseMarketplace)
	}
}
