const FB_SOURCE = 'files'; function normalizePath(path) { const raw = String(path || '/').trim(); const parts = raw.split('/').filter(Boolean); const clean = []; for (const part of parts) { if (part === '.') continue; if (part === '..') throw new Error('Invalid path'); clean.push(part); } return `/${clean.join('/')}`; } function joinPath(...parts) { return normalizePath(parts.join('/')); } function safeName(value) { return String(value || '') .trim() .replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-') .replace(/\s+/g, ' ') .replace(/^-+|-+$/g, ''); } function getConfig() { const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, ''); return { url, token: process.env.FILEBROWSER_TOKEN || '', clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/fourgebranding/Clients'), configured: Boolean(url), }; } async function fbFetch(config, method, endpoint, { params = {}, headers = {}, body } = {}) { const qs = new URLSearchParams({ source: FB_SOURCE, ...params }).toString(); const res = await fetch(`${config.url}${endpoint}?${qs}`, { method, headers: { Authorization: `Bearer ${config.token}`, ...headers }, body, }); if (!res.ok) { const text = await res.text(); const err = new Error(text || `FileBrowser ${res.status}`); err.status = res.status; throw err; } } async function mkdir(config, path) { await fbFetch(config, 'POST', '/api/resources', { params: { path, isDir: 'true' }, }).catch(() => {}); } async function renameFolder(config, fromPath, toPath) { await fbFetch(config, 'PATCH', '/api/resources', { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'rename', items: [{ fromSource: FB_SOURCE, fromPath, toSource: FB_SOURCE, toPath }], overwrite: false, }), }).catch(() => {}); } export default async function handler(req, res) { if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' }); const secret = process.env.SUPABASE_WEBHOOK_SECRET; if (secret) { const incoming = req.headers['x-webhook-secret'] || req.headers['x-supabase-webhook-secret'] || ''; if (incoming.trim() !== secret.trim()) return res.status(401).json({ error: 'Unauthorized' }); } const { type, record, old_record } = req.body || {}; if (!record?.title || !record?.project_name || !record?.company_name) { return res.status(200).json({ ok: true, skipped: 'missing title, project_name, or company_name' }); } const config = getConfig(); if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' }); const projectDir = joinPath(config.clientRoot, safeName(record.company_name), 'Projects', safeName(record.project_name)); // Ensure parent dirs exist await mkdir(config, joinPath(config.clientRoot, safeName(record.company_name))); await mkdir(config, joinPath(config.clientRoot, safeName(record.company_name), 'Projects')); await mkdir(config, projectDir); if (type === 'UPDATE' && old_record?.title && old_record.title !== record.title) { const oldPath = joinPath(projectDir, safeName(old_record.title)); const newPath = joinPath(projectDir, safeName(record.title)); await renameFolder(config, oldPath, newPath); } const taskDir = joinPath(projectDir, safeName(record.title)); await mkdir(config, taskDir); await mkdir(config, joinPath(taskDir, 'Working Files')); await mkdir(config, joinPath(taskDir, 'Request Info')); res.status(200).json({ ok: true, type, company: record.company_name, project: record.project_name, task: record.title }); }