// app/actions/jsonEditor.ts

"use server";

import fs 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");

export async function readJsonFile(filename: string) {
    try {
        const filePath = path.join(DATA_DIR, filename);
        const fileContent = await fs.readFile(filePath, 'utf-8');
        return { success: true, data: JSON.parse(fileContent) };
    } catch (error) {
        console.error(`Kunde inte läsa ${filename}:`, error);
        return { success: false, data: null };
    }
}

export async function writeJsonFile(filename: string, data: any) {
    try {
        const filePath = path.join(DATA_DIR, filename);
        await fs.mkdir(DATA_DIR, { recursive: true });

        await fs.writeFile(filePath, JSON.stringify(data, null, 4), 'utf-8');
        return { success: true };
    } catch (error) {
        console.error(`Kunde inte spara ${filename}:`, error);
        return { success: false, error: "Kunde inte spara filen." };
    }
}