const SftpClient = require("ssh2-sftp-client");

const SFTP_CONFIG = {
    host: process.env.SFTP_HOST,
    port: parseInt(process.env.SFTP_PORT) || 22,
    username: process.env.SFTP_USER,
    password: process.env.SFTP_PASSWORD,
    // privateKey: require("fs").readFileSync("/path/to/id_rsa"),
};

const REMOTE_DIR        = process.env.SFTP_REMOTE_DIR   || "/var/www/snapshots";
const SNAPSHOT_BASE_URL = process.env.SNAPSHOT_BASE_URL || "https://rcmedia.logiclane.tech";

const saveSnapshot = async (base64, recordId) => {
    if (!base64 || base64.trim() === "") return null;

    const sftp = new SftpClient();
    try {
        // Device sends raw JPEG base64 (no data:image/... prefix)
        // Strip prefix anyway just in case it ever gets added
        const raw = base64.replace(/^data:image\/\w+;base64,/, "").trim();
        const buffer = Buffer.from(raw, "base64");

        // Sanity check — JPEG magic bytes are FF D8
        if (buffer[0] !== 0xFF || buffer[1] !== 0xD8) {
            console.warn(`[snapshot] recordId=${recordId} — not a valid JPEG, skipping upload`);
            return null;
        }

        const filename   = `${recordId}_${Date.now()}.jpg`;
        const remotePath = `${REMOTE_DIR}/${filename}`;

        await sftp.connect(SFTP_CONFIG);
        await sftp.put(buffer, remotePath);

        const publicUrl = `${SNAPSHOT_BASE_URL}/${filename}`;
        console.log(`[snapshot] uploaded → ${publicUrl}`);
        return publicUrl;

    } catch (err) {
        console.error(`[snapshot] SFTP upload failed for recordId=${recordId}:`, err.message);
        return null; // never crash the webhook over a failed image upload
    } finally {
        await sftp.end().catch(() => {}); // silent close
    }
};

module.exports = { saveSnapshot };