import { Context } from '../types/context'

export interface MetricsQuery {
  resourceId: string
  metricType: string
  timeRange: {
    start: Date
    end: Date
  }
}

export async function getMetrics(context: Context, query: MetricsQuery) {
  const db = context.db
  const result = await db.query(
    `SELECT metric_type, value, timestamp, labels
     FROM metrics
     WHERE resource_id = $1 
       AND metric_type = $2
       AND timestamp >= $3
       AND timestamp <= $4
     ORDER BY timestamp ASC`,
    [query.resourceId, query.metricType, query.timeRange.start, query.timeRange.end]
  )

  const values = result.rows.map((row) => ({
    timestamp: row.timestamp,
    value: parseFloat(row.value),
    labels: typeof row.labels === 'string' ? JSON.parse(row.labels) : (row.labels || {}),
  }))

  // Get resource info
  const resourceResult = await db.query(
    'SELECT * FROM resource_inventory WHERE id = $1',
    [query.resourceId]
  )
  const resource = resourceResult.rows[0] || null

  return {
    resource,
    metricType: query.metricType,
    values,
    timeRange: query.timeRange,
  }
}

export async function recordMetric(
  context: Context,
  resourceId: string,
  metricType: string,
  value: number,
  labels?: Record<string, string>
) {
  const db = context.db
  await db.query(
    `INSERT INTO metrics (resource_id, metric_type, value, timestamp, labels)
     VALUES ($1, $2, $3, $4, $5)
     ON CONFLICT (resource_id, metric_type, timestamp) DO UPDATE
     SET value = EXCLUDED.value, labels = EXCLUDED.labels`,
    [resourceId, metricType, value, new Date(), JSON.stringify(labels || {})]
  )
}

