import { createClient } from '@supabase/supabase-js'; 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(() => {}); } async function requireTeamUser(authHeader) { const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL; const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY; if (!supabaseUrl || !supabaseAnonKey) return false; const client = createClient(supabaseUrl, supabaseAnonKey, { auth: { persistSession: false, autoRefreshToken: false }, global: { headers: { Authorization: authHeader } }, }); const { data: userData } = await client.auth.getUser(); if (!userData?.user) return false; const { data: profile } = await client.from('profiles').select('role').eq('id', userData.user.id).single(); return profile?.role === 'team'; } export default async function handler(req, res) { if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' }); const authHeader = req.headers.authorization || ''; const secret = process.env.SUPABASE_WEBHOOK_SECRET; if (authHeader.startsWith('Bearer ')) { const isTeam = await requireTeamUser(authHeader); if (!isTeam) return res.status(403).json({ error: 'Team members only' }); } else 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?.name || !record?.company_name) return res.status(200).json({ ok: true, skipped: 'missing name or company_name' }); const config = getConfig(); if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' }); const companyDir = joinPath(config.clientRoot, safeName(record.company_name)); const projectsDir = joinPath(companyDir, 'Projects'); // Ensure Clients/{company}/Projects/ exists await mkdir(config, companyDir); await mkdir(config, projectsDir); if (type === 'UPDATE' && old_record?.name && old_record.name !== record.name) { const oldPath = joinPath(projectsDir, safeName(old_record.name)); const newPath = joinPath(projectsDir, safeName(record.name)); await renameFolder(config, oldPath, newPath); } // Ensure folder for current project name exists const projectDir = joinPath(projectsDir, safeName(record.name)); await mkdir(config, projectDir); await mkdir(config, joinPath(projectDir, '00 Project Files')); res.status(200).json({ ok: true, type, company: record.company_name, project: record.name }); }