#!/usr/bin/env node
/**
 * BrandLoop – Schema-Check: listet Tabellen (Spalten-/Index-Status), Buckets
 * und Teams und meldet alles, was nicht "available" ist. Exit-Code 1 bei Problemen.
 * Aufruf wie setup-appwrite.mjs (Key aus env oder /home/webklar/apps/.env).
 */
import { readFileSync } from 'node:fs';

const ENDPOINT = process.env.APPWRITE_ENDPOINT || 'https://appwrite.webklar.com/v1';
const PROJECT = process.env.APPWRITE_PROJECT || '6a5cee34002bb8360c34';
const ENV_FILE = process.env.ENV_FILE || '/home/webklar/apps/.env';
const DB_ID = 'brandloop';

const API_KEY = process.env.APPWRITE_API_KEY
  || readFileSync(ENV_FILE, 'utf8').match(/^BRANDLOOP_APPWRITE_API_KEY=(.+)$/m)?.[1]?.trim();
if (!API_KEY) { console.error('Kein API-Key gefunden.'); process.exit(1); }

async function api(path) {
  const res = await fetch(`${ENDPOINT}${path}`, {
    headers: { 'X-Appwrite-Project': PROJECT, 'X-Appwrite-Key': API_KEY },
  });
  if (!res.ok) throw new Error(`GET ${path}: HTTP ${res.status}`);
  return res.json();
}

const limit = encodeURIComponent(JSON.stringify({ method: 'limit', values: [200] }));
let problems = 0;

const tables = await api(`/tablesdb/${DB_ID}/tables?queries[]=${limit}`);
for (const t of tables.tables) {
  const cols = await api(`/tablesdb/${DB_ID}/tables/${t.$id}/columns?queries[]=${limit}`);
  const idxs = await api(`/tablesdb/${DB_ID}/tables/${t.$id}/indexes?queries[]=${limit}`);
  const badC = cols.columns.filter(c => c.status !== 'available');
  const badI = idxs.indexes.filter(i => i.status !== 'available');
  console.log(`${t.$id.padEnd(18)} ${String(cols.columns.length).padStart(2)} Spalten, ${idxs.indexes.length} Indizes` +
    `${t.rowSecurity ? '' : '  [nur Team-Rechte]'}`);
  for (const c of badC) { problems++; console.log(`  ! Spalte ${c.key}: ${c.status} ${c.error || ''}`); }
  for (const i of badI) { problems++; console.log(`  ! Index ${i.key}: ${i.status} ${i.error || ''}`); }
}
console.log(`\nTabellen: ${tables.total}`);

const buckets = await api(`/storage/buckets?queries[]=${limit}`);
console.log(`Buckets:  ${buckets.total} (${buckets.buckets.map(b => b.$id).join(', ')})`);

const teams = await api(`/teams?queries[]=${limit}`);
console.log(`Teams:    ${teams.total} (${teams.teams.map(t => t.$id).join(', ')})`);

if (problems) { console.log(`\n${problems} Problem(e) gefunden.`); process.exit(1); }
console.log('\nAlles verfügbar.');
