import { Client, Databases } from 'node-appwrite'; const APPWRITE_ENDPOINT = process.env.APPWRITE_ENDPOINT || process.env.APPWRITE_FUNCTION_ENDPOINT; const APPWRITE_PROJECT_ID = process.env.APPWRITE_PROJECT_ID || process.env.APPWRITE_FUNCTION_PROJECT_ID; const APPWRITE_API_KEY = process.env.APPWRITE_API_KEY; const DATABASE_ID = process.env.APPWRITE_DATABASE_ID; const githubHeaders = (token) => ({ Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'appwrite-sync-github' }); export default async function ({ req, res, log, error }) { try { if (!APPWRITE_ENDPOINT || !APPWRITE_PROJECT_ID || !APPWRITE_API_KEY || !DATABASE_ID) { return res.json({ error: 'Missing Appwrite environment configuration.' }, 500); } const payload = req.body ? JSON.parse(req.body) : {}; const accountId = payload.accountId; const requesterId = (req.headers && (req.headers['x-appwrite-user-id'] || req.headers['x-appwrite-userid'])) || process.env.APPWRITE_FUNCTION_USER_ID || payload.userId; if (!accountId) { return res.json({ error: 'accountId is required in the request body.' }, 400); } const client = new Client() .setEndpoint(APPWRITE_ENDPOINT) .setProject(APPWRITE_PROJECT_ID) .setKey(APPWRITE_API_KEY); const databases = new Databases(client); const account = await databases.getDocument(DATABASE_ID, 'cloud_accounts', accountId); if (!account || account.provider !== 'github') { return res.json({ error: 'Cloud account not found or not a GitHub credential.' }, 404); } if (account.userId && requesterId && account.userId !== requesterId) { return res.json({ error: 'You are not allowed to use this credential.' }, 403); } const token = account.apiKey; if (!token) { return res.json({ error: 'GitHub token is missing for this account.' }, 400); } const githubResponse = await fetch('https://api.github.com/user/repos?per_page=100', { headers: githubHeaders(token) }); if (!githubResponse.ok) { const body = await githubResponse.text(); log(`GitHub API error: ${body}`); return res.json({ error: 'Failed to fetch repositories from GitHub.' }, githubResponse.status); } const repositories = await githubResponse.json(); const simplified = repositories.map((repo) => ({ id: repo.id, name: repo.name, fullName: repo.full_name, private: repo.private, url: repo.html_url, defaultBranch: repo.default_branch })); return res.json({ repositories: simplified }, 200); } catch (err) { error(err.message); return res.json({ error: 'Unexpected error while syncing with GitHub.' }, 500); } }