/**
 * Script zum Erstellen der Appwrite-Collection für Kontaktformulare.
 * Einmalig ausführen mit: node scripts/create-appwrite-collection.mjs
 *
 * Benötigt: API-Key aus Appwrite Console (Settings > API Keys)
 * Umgebungsvariable: APPWRITE_API_KEY=your-secret-key
 */

import { Client, Databases, Permission, Role } from "appwrite";

const ENDPOINT = "https://appwrite.webklar.com/v1";
const PROJECT_ID = "696b82270034001dab69";
const DATABASE_ID = "698124a20035e8f6dc42";
const COLLECTION_ID = "contact_submissions";

const apiKey = process.env.APPWRITE_API_KEY;
if (!apiKey) {
  console.error(
    "Fehler: APPWRITE_API_KEY Umgebungsvariable fehlt.\n" +
      "Beispiel: $env:APPWRITE_API_KEY='your-key'; node scripts/create-appwrite-collection.mjs"
  );
  process.exit(1);
}

const client = new Client().setEndpoint(ENDPOINT).setProject(PROJECT_ID).setKey(apiKey);
const databases = new Databases(client);

async function createCollection() {
  try {
    // 1. Collection erstellen
    // Permission: "any" darf Dokumente erstellen (für öffentliches Kontaktformular)
    await databases.createCollection(
      DATABASE_ID,
      COLLECTION_ID,
      "Kontaktanfragen",
      [Permission.create(Role.any())],
      true
    );
    console.log("✓ Collection erstellt:", COLLECTION_ID);

    // 2. Attribute hinzufügen (Appwrite erfordert kleine Wartezeit zwischen den Schritten)
    const delay = (ms) => new Promise((r) => setTimeout(r, ms));

    await databases.createStringAttribute(DATABASE_ID, COLLECTION_ID, "name", 256, true);
    await delay(500);
    await databases.createStringAttribute(DATABASE_ID, COLLECTION_ID, "email", 512, true);
    await delay(500);
    await databases.createStringAttribute(DATABASE_ID, COLLECTION_ID, "company", 256, false);
    await delay(500);
    await databases.createStringAttribute(DATABASE_ID, COLLECTION_ID, "message", 4096, true);

    console.log("✓ Attribute erstellt: name, email, company, message");
    console.log("\nCollection ist bereit. Kontaktformular kann jetzt genutzt werden.");
  } catch (err) {
    if (err.code === 409) {
      console.log("Collection existiert bereits:", COLLECTION_ID);
    } else {
      console.error("Fehler:", err.message || err);
      process.exit(1);
    }
  }
}

createCollection();
