const express = require('express');
const cors = require('cors');
const path = require('path');
const db = require('./db');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 3001;

// Middleware
app.use(cors());
// increase limit for large JSON payloads (e.g. base64 signature images)
app.use(express.json({ limit: '10mb' }));
app.use(express.static(path.join(__dirname, 'public')));

// API Routes for Form Fields
app.get('/api/fields', async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM form_fields ORDER BY order_index ASC');
        res.json(rows);
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to fetch fields' });
    }
});

app.post('/api/fields', async (req, res) => {
    const { label, type, options, is_required, order_index } = req.body;
    try {
        const [result] = await db.query(
            'INSERT INTO form_fields (label, type, options, is_required, order_index) VALUES (?, ?, ?, ?, ?)',
            [label, type, options ? JSON.stringify(options) : null, is_required, order_index || 0]
        );
        res.status(201).json({ id: result.insertId, label, type, options, is_required, order_index });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to add field' });
    }
});

app.put('/api/fields/:id', async (req, res) => {
    const { id } = req.params;
    const { label, type, options, is_required, order_index } = req.body;
    try {
        await db.query(
            'UPDATE form_fields SET label = ?, type = ?, options = ?, is_required = ?, order_index = ? WHERE id = ?',
            [label, type, options ? JSON.stringify(options) : null, is_required, order_index, id]
        );
        res.json({ message: 'Field updated' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to update field' });
    }
});

app.delete('/api/fields/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await db.query('DELETE FROM form_fields WHERE id = ?', [id]);
        res.json({ message: 'Field deleted' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to delete field' });
    }
});

// API Routes for Responses
app.get('/api/responses', async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM responses ORDER BY created_at DESC');
        res.json(rows);
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to fetch responses' });
    }
});

app.post('/api/responses', async (req, res) => {
    const { data } = req.body;
    try {
        const [result] = await db.query(
            'INSERT INTO responses (data) VALUES (?)',
            [JSON.stringify(data)]
        );
        res.status(201).json({ id: result.insertId, message: 'Response submitted' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to submit response' });
    }
});

app.delete('/api/responses/bulk', async (req, res) => {
    const { ids } = req.body;
    if (!Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({ error: 'No IDs provided' });
    }
    try {
        await db.query('DELETE FROM responses WHERE id IN (?)', [ids]);
        res.json({ message: 'Responses deleted' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to delete responses' });
    }
});

// Fallback to index.html for SPA like behavior
app.use((req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Start the server
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});
