// Package slowquery provides implementation of query on slow log files.
// Slow log files of the user TiDB cluster is written to S3 via tidbcloud/vector.
package topsqlv2

import (
	"context"
	"errors"
	"fmt"

	"github.com/tidbcloud/observability/o11ydiagnosis/pkg/storage"
)

var ErrUnsupportedOrderBy = errors.New("unsupported order by")

// FieldInfo represents information about a field/column in a table
type FieldInfo struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

// duckDBAdapter is an interface for querying slow logs.
type duckDBAdapter interface {
	SelectSlowlogInDLWithoutFilterPushdown(ctx context.Context, dest interface{}, tableAlias, table, query string) error
}

// NewSlowQuery creates a new SlowQuery implementation.
func NewSQLsQuery(store storage.Storage) duckDBAdapter {
	return &sqlsQuery{
		store: store,
	}
}

type sqlsQuery struct {
	store storage.Storage
}

func (s *sqlsQuery) SelectSlowlogInDLWithoutFilterPushdown(ctx context.Context, dest interface{}, tableAlias, table, query string) error {
	return fmt.Errorf("not implemented")
}

type ClusterHeader struct {
	Provider   *string `header:"x-provider"`
	Region     *string `header:"x-region"`
	TenantID   *string `header:"x-org-id"`
	ProjectID  *string `header:"x-project-id,omitempty"`
	ClusterID  *string `header:"x-cluster-id"`
	DeployType *string `header:"x-deploy-type"` // "dedicated" or "shared"
	Env        *string `header:"x-env"`
	BizType    *string `header:"x-biz-type"`
}

const (
	TierDedicated = "dedicated"
	TierShared    = "shared"
	TierNextGen   = "nextgen"
	TierPremium   = "premium"
)

func (h *ClusterHeader) Validate() error {
	if h.Provider == nil {
		return errors.New("provider not found")
	}
	if h.Region == nil {
		return errors.New("region not found")
	}
	if h.TenantID == nil {
		return errors.New("org id not found")
	}
	if h.ProjectID == nil {
		var emptyString string
		h.ProjectID = &emptyString
	}
	if h.ClusterID == nil || *h.ClusterID == "" {
		return errors.New("cluster id not found")
	}
	if h.DeployType == nil {
		return errors.New("deploy type not found")
	}
	if h.Env == nil {
		prodString := "prod"
		h.Env = &prodString
	}
	if h.BizType == nil {
		bizType := "unknown"
		h.BizType = &bizType
	}

	return nil
}
