// app/actions/files.ts
'use server';

import crypto from 'crypto';
import fs from 'fs';
import fsPromises from 'fs/promises';
import path from 'path';

const isProd = process.env.NODE_ENV === "production";
const DATA_DIR = isProd ? "/app/data" : path.join(process.cwd(), "app/data");
const FILES_DIR = path.join(DATA_DIR, "files");

const generateFileHash = (filePath: string): Promise<string> => {
    return new Promise((resolve, reject) => {
        const hash = crypto.createHash('md5');
        const stream = fs.createReadStream(filePath);

        stream.on('error', (err) => reject(err));
        stream.on('data', (chunk) => hash.update(chunk));
        stream.on('end', () => resolve(hash.digest('hex').substring(0, 8)));
    });
};

export async function getLocalFileMeta(fileUrl: string) {
    try {
        const cleanName = decodeURIComponent(fileUrl.split('/').pop() || '');
        const fullPath = path.join(FILES_DIR, cleanName);
        const stats = await fsPromises.stat(fullPath);
        const sizeMb = (stats.size / (1024 * 1024)).toFixed(2) + ' MB';
        const fileHash = await generateFileHash(fullPath);

        return { size: sizeMb, version: fileHash };
    } catch (error) {
        console.error(`Kunde inte läsa filen (actions): ${fileUrl}`, error);
        return { size: "Okänd", version: "v1" };
    }
}