"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalStorageBackend = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const mime_1 = require("./mime");
const BASE_DIR = process.env.LT_FILE_STORAGE_DIR || './data/files';
function resolveAndValidate(filePath) {
    const relative = filePath.replace(/^\/+/, '');
    const resolved = path.resolve(BASE_DIR, relative);
    const base = path.resolve(BASE_DIR);
    if (!resolved.startsWith(base + path.sep) && resolved !== base) {
        throw new Error(`Path traversal denied: ${filePath}`);
    }
    return resolved;
}
function ensureBaseDir() {
    if (!fs.existsSync(BASE_DIR)) {
        fs.mkdirSync(BASE_DIR, { recursive: true });
    }
}
class LocalStorageBackend {
    async write(key, data) {
        ensureBaseDir();
        const resolved = resolveAndValidate(key);
        const dir = path.dirname(resolved);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        fs.writeFileSync(resolved, data);
        return { ref: key, size: data.length };
    }
    async read(key) {
        const resolved = resolveAndValidate(key);
        if (!fs.existsSync(resolved)) {
            throw new Error(`File not found: ${key}`);
        }
        const data = fs.readFileSync(resolved);
        return { data, size: data.length };
    }
    async list(prefix, pattern) {
        ensureBaseDir();
        const dir = prefix
            ? resolveAndValidate(prefix)
            : path.resolve(BASE_DIR);
        if (!fs.existsSync(dir)) {
            return { files: [] };
        }
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        const files = [];
        for (const entry of entries) {
            if (!entry.isFile())
                continue;
            if (pattern && !entry.name.match(new RegExp(pattern.replace(/\*/g, '.*'))))
                continue;
            const fullPath = path.join(dir, entry.name);
            const stat = fs.statSync(fullPath);
            const relativePath = path.relative(path.resolve(BASE_DIR), fullPath);
            files.push({
                path: relativePath,
                size: stat.size,
                modified_at: stat.mtime.toISOString(),
            });
        }
        return { files };
    }
    async delete(key) {
        const resolved = resolveAndValidate(key);
        if (!fs.existsSync(resolved)) {
            return { deleted: false };
        }
        fs.unlinkSync(resolved);
        return { deleted: true };
    }
    async getLocalPath(key) {
        ensureBaseDir();
        const resolved = resolveAndValidate(key);
        const dir = path.dirname(resolved);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        return resolved;
    }
    async commitLocalPath(_key, _localPath) {
        // No-op for local backend — file is already in its final location
        const stat = fs.statSync(_localPath);
        return { size: stat.size };
    }
    async createReadStream(key) {
        const resolved = resolveAndValidate(key);
        if (!fs.existsSync(resolved)) {
            throw new Error(`File not found: ${key}`);
        }
        return fs.createReadStream(resolved);
    }
    async listWithPrefixes(prefix, pageSize, continuationToken) {
        ensureBaseDir();
        const dir = prefix ? resolveAndValidate(prefix) : path.resolve(BASE_DIR);
        if (!fs.existsSync(dir)) {
            return { files: [], directories: [] };
        }
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        const limit = pageSize || 100;
        const offset = continuationToken ? parseInt(continuationToken, 10) : 0;
        const allDirs = [];
        const allFiles = [];
        for (const entry of entries) {
            const relativePath = path.relative(path.resolve(BASE_DIR), path.join(dir, entry.name));
            if (entry.isDirectory()) {
                allDirs.push(relativePath + '/');
            }
            else if (entry.isFile()) {
                const stat = fs.statSync(path.join(dir, entry.name));
                allFiles.push({
                    path: relativePath,
                    size: stat.size,
                    modified_at: stat.mtime.toISOString(),
                });
            }
        }
        // Directories first, then files — paginate the combined list
        const combined = [...allDirs.map((d) => ({ type: 'dir', value: d })),
            ...allFiles.map((f) => ({ type: 'file', value: f }))];
        const page = combined.slice(offset, offset + limit);
        const hasMore = offset + limit < combined.length;
        const directories = page.filter((e) => e.type === 'dir').map((e) => e.value);
        const files = page.filter((e) => e.type === 'file').map((e) => e.value);
        return {
            files,
            directories,
            nextToken: hasMore ? String(offset + limit) : undefined,
        };
    }
    async getMetadata(key) {
        const resolved = resolveAndValidate(key);
        if (!fs.existsSync(resolved)) {
            throw new Error(`File not found: ${key}`);
        }
        const stat = fs.statSync(resolved);
        return {
            size: stat.size,
            modified_at: stat.mtime.toISOString(),
            content_type: (0, mime_1.mimeFromPath)(key),
        };
    }
    async getSignedUrl(key, expiresInSeconds) {
        const secret = process.env.JWT_SECRET;
        if (!secret) {
            throw new Error('JWT_SECRET not configured — cannot generate signed URLs');
        }
        const token = jsonwebtoken_1.default.sign({ filePath: key.replace(/^\/+/, ''), purpose: 'file-download' }, secret, { expiresIn: expiresInSeconds });
        return `/api/files/${key.replace(/^\/+/, '')}?token=${token}`;
    }
}
exports.LocalStorageBackend = LocalStorageBackend;
