import { TransformNullValue, Query } from '@diag-ui/chart'

export type Schema = {
  queries: Query[]
  unit: string
  title: string
  nullValue?: TransformNullValue
  subQueries?: Omit<Schema, 'title'>
}
export type Schemas = Schema[]
export type SegmentSchemas = { title: string; schemas: Schemas }[]

const TiDBQPSSchema: Schema = {
  title: 'QPS',
  unit: 'short',
  nullValue: TransformNullValue.AS_ZERO,
  queries: [
    {
      name: '{cluster_id}',
      promql: `sum by (cluster_id) (rate(tidb_executor_statement_total{{label_tenant_id}}[1h]))`,
      type: 'line'
    }
  ]
}

const TiKVStorageSizeSchema: Schema = {
  title: 'TiKV Storage Size',
  queries: [
    {
      promql:
        'sum by (cluster_id) (avg_over_time(tikv_engine_size_bytes{{label_tenant_id}}[1h]))',
      name: '{cluster_id}',
      type: 'line'
    }
  ],
  nullValue: TransformNullValue.AS_ZERO,
  unit: 'bytes'
}

const TiFlashStorageSizeSchema: Schema = {
  title: 'TiFlash Storage Size',
  queries: [
    {
      promql:
        'sum by (cluster_id) (avg_over_time(tiflash_system_current_metric_StoreSizeCapacity{{label_tenant_id}}[1h]))',
      name: '{cluster_id}',
      type: 'line'
    }
  ],
  nullValue: TransformNullValue.AS_ZERO,
  unit: 'bytes'
}

export const defaultSchemas: Schemas = [
  TiDBQPSSchema,
  TiKVStorageSizeSchema,
  TiFlashStorageSizeSchema
]

export const schemasMap: {
  [k: string]: Schemas | SegmentSchemas
} = {
  default: defaultSchemas
}

export const isSegmentSchemas = (
  s: Schemas | SegmentSchemas
): s is SegmentSchemas => {
  return !!(s as SegmentSchemas)[0].schemas
}
