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" });
  }
});

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