import { query } from '../../../db/client.js'
import {
  getAgisoMessagingDefaults,
  getAgisoShopConfigMap,
  getAgisoShopsFilePath,
  saveAgisoMessagingConfig,
} from '../../platforms/agiso/shop-config-service.js'
import { resolveDisplayShopName } from '../admin-read-shared-helpers.js'
import {
  mapAdminAgisoMessagingDefaults,
  mapAdminAgisoShopConfigItem,
} from './domain.js'
import { buildAdminAgisoMessagingSavePayload } from './writes.js'

type JsonObject = Record<string, any>

export async function getAdminAgisoShopConfigs() {
  const configMap = getAgisoShopConfigMap()
  const defaults = getAgisoMessagingDefaults()
  const rowsResult = await query(
    `
      SELECT
        shop_id,
        MAX(CASE WHEN trim(shop_name) != '' THEN shop_name ELSE '' END) AS detected_shop_name,
        MAX(created_at) AS latest_seen_at,
        COUNT(*)::int AS webhook_event_count
      FROM webhook_events
      WHERE provider = 'agiso' AND trim(shop_id) != ''
      GROUP BY shop_id
      ORDER BY latest_seen_at DESC, shop_id DESC
    `,
  )
  const rows = rowsResult.rows

  return {
    filePath: getAgisoShopsFilePath(),
    defaults: mapAdminAgisoMessagingDefaults(defaults),
    shops: Object.entries(configMap)
      .sort(([left], [right]) => left.localeCompare(right))
      .map(([shopId, config]) => mapAdminAgisoShopConfigItem(shopId, config)),
    observedShops: rows.map((row) => ({
      shopId: String(row.shop_id || '').trim(),
      detectedShopName: String(row.detected_shop_name || '').trim(),
      displayShopName: resolveDisplayShopName('agiso', row.shop_id, row.detected_shop_name),
      latestSeenAt: row.latest_seen_at || null,
      webhookEventCount: Number(row.webhook_event_count || 0),
      configured: Boolean(configMap[String(row.shop_id || '').trim()]),
    })),
  }
}

export function updateAdminAgisoShopConfigs(payload: JsonObject = {}) {
  const saved = saveAgisoMessagingConfig(buildAdminAgisoMessagingSavePayload(payload, {
    currentDefaults: getAgisoMessagingDefaults(),
    currentMap: getAgisoShopConfigMap(),
  }))

  return {
    filePath: getAgisoShopsFilePath(),
    defaults: mapAdminAgisoMessagingDefaults(saved.defaults),
    shops: Object.entries(saved.shops)
      .sort(([left], [right]) => left.localeCompare(right))
      .map(([shopId, config]) => mapAdminAgisoShopConfigItem(shopId, config)),
  }
}
