import express from "express";
import { Client, Account, Databases } from "node-appwrite";
import dotenv from "dotenv";

dotenv.config();

const app = express();
app.use(express.json());

const PORT = process.env.PORT || 3000;

function makeUserClient(jwt) {
  const client = new Client()
    .setEndpoint(process.env.APPWRITE_ENDPOINT)
    .setProject(process.env.APPWRITE_PROJECT_ID)
    .setJWT(jwt);
  return client;
}

function makeAdminClient() {
  const client = new Client()
    .setEndpoint(process.env.APPWRITE_ENDPOINT)
    .setProject(process.env.APPWRITE_PROJECT_ID)
    .setKey(process.env.APPWRITE_API_KEY);
  return client;
}

app.post("/api/action", async (req, res) => {
  try {
    const auth = req.headers.authorization || "";
    const jwt = auth.startsWith("Bearer ") ? auth.slice(7) : "";
    if (!jwt) return res.status(401).json({ ok: false, error: "missing token" });

    // 1) user token validieren
    const userClient = makeUserClient(jwt);
    const account = new Account(userClient);
    const user = await account.get(); // wirft Fehler, wenn JWT ungueltig/abgelaufen

    // 2) privilegierte Aktion nur serverseitig mit Admin Key
    const adminClient = makeAdminClient();
    const db = new Databases(adminClient);

    // Beispiel: lies etwas, das nur du lesen darfst
    // const data = await db.listDocuments("dbId", "collectionId");

    return res.json({ ok: true, userId: user.$id, info: "action allowed" });
  } catch (e) {
    return res.status(401).json({ ok: false, error: "unauthorized" });
  }
});

// Endpoint: Setze user_extension_load auf true
app.post("/api/user/set-extension-loaded", async (req, res) => {
  try {
    const auth = req.headers.authorization || "";
    const jwt = auth.startsWith("Bearer ") ? auth.slice(7) : "";
    if (!jwt) return res.status(401).json({ ok: false, error: "missing token" });

    // 1) User token validieren
    const userClient = makeUserClient(jwt);
    const account = new Account(userClient);
    const user = await account.get();

    // 2) User-Dokument mit Admin Key aktualisieren
    const adminClient = makeAdminClient();
    const db = new Databases(adminClient);
    const databaseId = process.env.APPWRITE_DATABASE_ID || "eship-db";
    const usersCollectionId = process.env.APPWRITE_USERS_COLLECTION_ID || "users";

    // Update user document: setze user_extension_load auf true
    await db.updateDocument(
      databaseId,
      usersCollectionId,
      user.$id,
      {
        user_extension_load: true
      }
    );

    return res.json({ ok: true, userId: user.$id });
  } catch (e) {
    console.error("Error in /api/user/set-extension-loaded:", e);
    return res.status(401).json({ ok: false, error: "unauthorized" });
  }
});

app.listen(PORT, () => {
  console.log(`Backend server running on port ${PORT}`);
});
