import { resolve, basename } from "node:path";
import { readFile, stat } from "node:fs/promises";
import { realpathSync } from "node:fs";
import { parseICS } from "../lib/ics.js";
const MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024; // 20 MB — matches attachment upload limit
export async function scheduleImportIcs(filePath, accountId) {
    // --- Path containment: must be within the account directory ---
    const platformRoot = process.env.PLATFORM_ROOT;
    if (!platformRoot) {
        throw new Error("PLATFORM_ROOT environment variable is required");
    }
    const accountDir = resolve(platformRoot, "..", "data/accounts", accountId);
    let resolvedPath;
    try {
        resolvedPath = realpathSync(filePath);
        const accountResolved = realpathSync(accountDir);
        if (!resolvedPath.startsWith(accountResolved + "/")) {
            console.error(`[schedule-import-ics] path validation failed: outside account directory`);
            throw new Error("Access denied: file is outside the account directory");
        }
    }
    catch (err) {
        if (err.code === "ENOENT") {
            console.error(`[schedule-import-ics] path validation failed: file not found`);
            throw new Error(`File not found: ${filePath}`);
        }
        throw err;
    }
    // --- Size check ---
    const fileStat = await stat(resolvedPath);
    if (fileStat.size > MAX_FILE_SIZE_BYTES) {
        console.error(`[schedule-import-ics] path validation failed: file too large (${fileStat.size} bytes)`);
        throw new Error(`File too large: ${fileStat.size} bytes (max ${MAX_FILE_SIZE_BYTES})`);
    }
    // --- Read and parse ---
    const content = await readFile(resolvedPath, "utf-8");
    const result = parseICS(content);
    console.error(`[schedule-import-ics] path=${resolvedPath} parsedEvents=${result.events.length} parseErrors=${result.parseErrors.length}`);
    for (const err of result.parseErrors) {
        console.error(`[schedule-import-ics] parse error: ${err}`);
    }
    return {
        events: result.events,
        parseErrors: result.parseErrors,
        filename: basename(resolvedPath),
    };
}
//# sourceMappingURL=schedule-import-ics.js.map