'use strict'; const fs = require('fs'); const path = require('path'); const { AppError } = require('../../core/errors'); const { log: auditLog } = require('../../core/audit'); const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads'); async function getOrg(models, orgId) { const org = await models.Organization.findByPk(orgId); if (!org) throw new AppError('NOT_FOUND', 'Organization not found.', 404); return org; } async function updateOrg(models, req, orgId, data) { if (data.timezone) { const valid = Intl.supportedValuesOf('timeZone'); if (!valid.includes(data.timezone)) { throw new AppError('VALIDATION_FAILED', 'Invalid timezone.', 400, 'timezone'); } } const org = await getOrg(models, orgId); await org.update(data); await auditLog(req, 'org.update', 'organization', orgId, data); return org; } async function getBranding(models, orgId) { let branding = await models.Branding.findOne({ where: { organizationId: orgId } }); if (!branding) { branding = await models.Branding.create({ organizationId: orgId }); } return branding; } async function updateBranding(models, req, orgId, data) { const branding = await getBranding(models, orgId); await branding.update(data); await auditLog(req, 'branding.update', 'branding', branding.id, data); return branding; } async function uploadLogo(models, req, orgId, file) { const { fileTypeFromBuffer } = await import('file-type'); const ALLOWED = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']; const EXT_MAP = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp' }; let detectedMime; try { const fd = fs.openSync(file.path, 'r'); const buf = Buffer.alloc(12); fs.readSync(fd, buf, 0, 12, 0); fs.closeSync(fd); const result = await fileTypeFromBuffer(buf); detectedMime = result?.mime; } catch { await fs.promises.unlink(file.path).catch(() => {}); throw new AppError('UPLOAD_TYPE_INVALID', 'Could not read uploaded file.', 400); } if (!detectedMime || !ALLOWED.includes(detectedMime)) { await fs.promises.unlink(file.path).catch(() => {}); throw new AppError('UPLOAD_TYPE_INVALID', 'Only PNG, JPG, GIF, and WebP images are supported.', 400); } const ext = EXT_MAP[detectedMime]; const safeName = `logo_${orgId}_${Date.now()}${ext}`; const destPath = path.join(UPLOADS_DIR(), safeName); const branding = await getBranding(models, orgId); // Delete old logo if (branding.logoPath) { const oldFile = path.join(UPLOADS_DIR(), path.basename(branding.logoPath)); await fs.promises.unlink(oldFile).catch(() => {}); } await fs.promises.rename(file.path, destPath); await branding.update({ logoPath: `/api/v1/org/logo` }); await auditLog(req, 'logo.upload', 'branding', branding.id, { filename: safeName }); return branding; } module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo };