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 basename(path) { const parts = normalizePath(path).split('/').filter(Boolean); return parts[parts.length - 1] || ''; } function parentDir(path) { const parts = normalizePath(path).split('/').filter(Boolean); parts.pop(); return `/${parts.join('/')}`; } function getFbConfig() { 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'), archiveRoot: normalizePath(process.env.FILEBROWSER_ARCHIVE_ROOT || '/fourgebranding/Archive'), configured: Boolean(url) && Boolean(process.env.FILEBROWSER_TOKEN), }; } 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; } const text = await res.text(); try { return text ? JSON.parse(text) : null; } catch { return text; } } async function fbExists(config, path) { try { await fbFetch(config, 'GET', '/api/resources', { params: { path } }); return true; } catch (e) { if (e.status === 404) return false; throw e; } } async function fbMkdir(config, path) { await fbFetch(config, 'POST', '/api/resources', { params: { path, isDir: 'true' } }).catch(() => {}); } async function mergeMove(config, fbSrc, fbDstParent) { const name = basename(fbSrc); const fbDst = joinPath(fbDstParent, name); const destExists = await fbExists(config, fbDst); if (!destExists) { await fbFetch(config, 'PATCH', '/api/resources', { params: {}, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'move', items: [{ fromSource: FB_SOURCE, fromPath: fbSrc, toSource: FB_SOURCE, toPath: fbDst }], overwrite: false, }), }); } else { const data = await fbFetch(config, 'GET', '/api/resources', { params: { path: fbSrc } }); const dirs = (data?.folders || []).map(f => f.name); const files = (data?.files || []).map(f => f.name); await fbMkdir(config, fbDst); for (const dir of dirs) await mergeMove(config, joinPath(fbSrc, dir), fbDst); for (const file of files) { await fbFetch(config, 'PATCH', '/api/resources', { params: {}, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'move', items: [{ fromSource: FB_SOURCE, fromPath: joinPath(fbSrc, file), toSource: FB_SOURCE, toPath: joinPath(fbDst, file) }], overwrite: true, }), }).catch(() => {}); } await fbFetch(config, 'DELETE', '/api/resources', { params: { path: fbSrc } }).catch(() => {}); } } async function archiveProject(companyName, projectName) { const config = getFbConfig(); if (!config.configured || !companyName || !projectName) return; const co = safeName(companyName); const proj = safeName(projectName); // Ensure archive dirs exist await fbMkdir(config, config.archiveRoot); await fbMkdir(config, joinPath(config.archiveRoot, 'Clients')); await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', co)); await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', co, 'Projects')); // Merge-move project folder into archive const srcPath = joinPath(config.clientRoot, co, 'Projects', proj); const dstParentPath = joinPath(config.archiveRoot, 'Clients', co, 'Projects'); await mergeMove(config, srcPath, dstParentPath); } export default async function handler(req, res) { if (req.method !== 'DELETE') return res.status(405).json({ error: 'Method not allowed' }); const authHeader = req.headers.authorization || ''; if (!authHeader.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized' }); const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL; const anonKey = process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY; const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; const callerClient = createClient(supabaseUrl, anonKey, { auth: { persistSession: false, autoRefreshToken: false }, global: { headers: { Authorization: authHeader } }, }); const { data: userData } = await callerClient.auth.getUser(); if (!userData?.user) return res.status(401).json({ error: 'Unauthorized' }); const { data: profile } = await callerClient.from('profiles').select('id, role').eq('id', userData.user.id).single(); if (!profile || !['team', 'client'].includes(profile.role)) return res.status(403).json({ error: 'Forbidden' }); const projectId = req.query.id; if (!projectId) return res.status(400).json({ error: 'Project ID required' }); const admin = createClient(supabaseUrl, serviceKey, { auth: { persistSession: false, autoRefreshToken: false }, }); // Fetch project + company name before deletion (needed for archive path) const { data: projRecord } = await admin .from('projects') .select('id, name, company:companies(name)') .eq('id', projectId) .single(); if (!projRecord) return res.status(404).json({ error: 'Project not found' }); // For clients, confirm they can see this project (RLS gate) if (profile.role === 'client') { const { data: proj, error: projErr } = await callerClient.from('projects').select('id').eq('id', projectId).single(); if (projErr || !proj) return res.status(404).json({ error: 'Project not found or access denied' }); } // Cleanup storage files const { data: tasks } = await admin.from('tasks').select('id').eq('project_id', projectId); const taskIds = (tasks || []).map(t => t.id); if (taskIds.length) { const { data: subs } = await admin.from('submissions').select('id').in('task_id', taskIds); const subIds = (subs || []).map(s => s.id); if (subIds.length) { const { data: subFiles } = await admin.from('submission_files').select('storage_path').in('submission_id', subIds); const subPaths = (subFiles || []).map(f => f.storage_path).filter(Boolean); if (subPaths.length) await admin.storage.from('submissions').remove(subPaths); const { data: deliveries } = await admin.from('deliveries').select('id').in('submission_id', subIds); const delIds = (deliveries || []).map(d => d.id); if (delIds.length) { const { data: delFiles } = await admin.from('delivery_files').select('storage_path').in('delivery_id', delIds); const delPaths = (delFiles || []).map(f => f.storage_path).filter(Boolean); if (delPaths.length) await admin.storage.from('deliveries').remove(delPaths); } } } // Delete project (DB cascade handles tasks/submissions/etc.) const { error } = await admin.from('projects').delete().eq('id', projectId); if (error) return res.status(500).json({ error: error.message }); // Archive FileBrowser project folder (server-side, so errors are logged) try { await archiveProject(projRecord.company?.name, projRecord.name); } catch (e) { console.error('[delete-project] archive failed:', e.message); // Don't fail — DB delete succeeded } return res.status(200).json({ ok: true }); }