import { query } from '../db/client.js'

export type AppConfigEntryRow = {
  config_key: string
  config_json: unknown
  source_file_path: string
  migrated_from_file: boolean
  created_at: string
  updated_at: string
}

type UpsertAppConfigEntryInput = {
  configKey: string
  configJson: unknown
  sourceFilePath?: string | undefined
  migratedFromFile?: boolean
  timestamp: string
}

export async function listAppConfigEntries(): Promise<AppConfigEntryRow[]> {
  const result = await query<AppConfigEntryRow>(
    `
      SELECT *
      FROM app_config_entries
      ORDER BY config_key ASC
    `,
  )

  return result.rows
}

export async function upsertAppConfigEntry(
  input: UpsertAppConfigEntryInput,
): Promise<AppConfigEntryRow | null> {
  const result = await query<AppConfigEntryRow>(
    `
      INSERT INTO app_config_entries (
        config_key,
        config_json,
        source_file_path,
        migrated_from_file,
        created_at,
        updated_at
      ) VALUES ($1, $2::jsonb, $3, $4, $5, $6)
      ON CONFLICT (config_key) DO UPDATE
      SET
        config_json = EXCLUDED.config_json,
        source_file_path = CASE
          WHEN EXCLUDED.source_file_path <> '' THEN EXCLUDED.source_file_path
          ELSE app_config_entries.source_file_path
        END,
        migrated_from_file = app_config_entries.migrated_from_file OR EXCLUDED.migrated_from_file,
        updated_at = EXCLUDED.updated_at
      RETURNING *
    `,
    [
      String(input.configKey || '').trim(),
      JSON.stringify(input.configJson ?? {}),
      String(input.sourceFilePath || '').trim(),
      input.migratedFromFile === true,
      input.timestamp,
      input.timestamp,
    ],
  )

  return result.rows[0] || null
}
