const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs-extra');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3001;
const DATA_FILE = path.join(__dirname, 'changelog-data.json');

// Middleware
app.use(cors());
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

async function ensureDataFile() {
    if (!await fs.pathExists(DATA_FILE)) {
        await fs.writeJson(DATA_FILE, {
            versions: [],
            changelogs: {}
        }, { spaces: 2 });
    }
}

async function readData() {
    await ensureDataFile();
    return await fs.readJson(DATA_FILE);
}

async function writeData(data) {
    await fs.writeJson(DATA_FILE, data, { spaces: 2 });
}

app.get('/api/changelog/versions', async (req, res) => {
    try {
        const data = await readData();
        res.json(data.versions || []);
    } catch (error) {
        console.error('Error fetching versions:', error);
        res.status(500).json({ error: 'Failed to fetch versions' });
    }
});

app.get('/api/changelog/versions/:version(*)', async (req, res) => {
    try {
        const version = decodeURIComponent(req.params.version);
        console.log('Fetching version:', version);
        const data = await readData();
        const content = data.changelogs?.[version] || '';
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        res.send(content);
    } catch (error) {
        console.error('Error fetching version content:', error);
        res.status(500).send('Failed to fetch version content');
    }
});

app.post('/api/changelog/versions', async (req, res) => {
    try {
        const { version, content } = req.body;
        console.log('Creating version:', version, 'Content length:', content?.length);

        if (!version || !content) {
            return res.status(400).json({ error: 'Version and content are required' });
        }

        const data = await readData();

        if (!data.versions.includes(version)) {
            data.versions.unshift(version);
        }

        if (!data.changelogs) {
            data.changelogs = {};
        }
        data.changelogs[version] = content;

        await writeData(data);
        console.log('Version created successfully:', version);
        res.status(200).json({ success: true, version });
    } catch (error) {
        console.error('Error creating version:', error);
        res.status(500).json({ error: 'Failed to create version', message: error.message });
    }
});

app.put('/api/changelog/versions/:version(*)', async (req, res) => {
    try {
        const version = decodeURIComponent(req.params.version);
        const { content, newVersion } = req.body;
        console.log('Updating version:', version, 'New version:', newVersion, 'Content length:', content?.length);

        const data = await readData();

        if (newVersion && newVersion !== version) {
            if (data.changelogs?.[version]) {
                data.changelogs[newVersion] = data.changelogs[version];
                delete data.changelogs[version];
            }

            const index = data.versions.indexOf(version);
            if (index !== -1) {
                data.versions[index] = newVersion;
            }
        }

        if (content !== undefined) {
            if (!data.changelogs) {
                data.changelogs = {};
            }
            const targetVersion = newVersion || version;
            data.changelogs[targetVersion] = content;
        }

        await writeData(data);
        console.log('Version updated successfully:', newVersion || version);
        res.status(200).json({ success: true, version: newVersion || version });
    } catch (error) {
        console.error('Error updating version:', error);
        res.status(500).json({ error: 'Failed to update version', message: error.message });
    }
});

app.delete('/api/changelog/versions/:version(*)', async (req, res) => {
    try {
        const version = decodeURIComponent(req.params.version);
        console.log('Deleting version:', version);
        const data = await readData();

        data.versions = data.versions.filter(v => v !== version);

        if (data.changelogs?.[version]) {
            delete data.changelogs[version];
        }

        await writeData(data);
        console.log('Version deleted successfully:', version);
        res.status(200).json({ success: true });
    } catch (error) {
        console.error('Error deleting version:', error);
        res.status(500).json({ error: 'Failed to delete version', message: error.message });
    }
});

app.get('/api/changelog/admin/all', async (req, res) => {
    try {
        const data = await readData();
        res.json(data);
    } catch (error) {
        console.error('Error fetching all data:', error);
        res.status(500).json({ error: 'Failed to fetch data' });
    }
});

async function startServer() {
    await ensureDataFile();
    app.listen(PORT, () => {
        console.log(`F17 Changelog API Server running on http://localhost:${PORT}`);
        console.log(`Admin Editor: http://localhost:${PORT}/admin.html`);
    });
}

startServer();
