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

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

app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

app.get('/api/recipes', (req, res) => {
  db.all('SELECT id, name, ingredients, instructions, created_at FROM recipes ORDER BY id DESC', (err, rows) => {
    if (err) {
      return res.status(500).json({ error: 'Failed to load recipes' });
    }

    const recipes = rows.map((row) => ({
      ...row,
      ingredients: row.ingredients
        .split('\n')
        .map((item) => item.trim())
        .filter(Boolean)
    }));

    return res.json(recipes);
  });
});

app.post('/api/recipes', (req, res) => {
  const { name, ingredients, instructions } = req.body;

  if (!name || !instructions || !Array.isArray(ingredients) || ingredients.length === 0) {
    return res.status(400).json({ error: 'name, ingredients[], and instructions are required' });
  }

  const cleanName = String(name).trim();
  const cleanInstructions = String(instructions).trim();
  const cleanIngredients = ingredients
    .map((item) => String(item).trim())
    .filter(Boolean);

  if (!cleanName || !cleanInstructions || cleanIngredients.length === 0) {
    return res.status(400).json({ error: 'Please provide non-empty fields' });
  }

  const sql = 'INSERT INTO recipes (name, ingredients, instructions) VALUES (?, ?, ?)';
  db.run(sql, [cleanName, cleanIngredients.join('\n'), cleanInstructions], function onInsert(err) {
    if (err) {
      return res.status(500).json({ error: 'Failed to save recipe' });
    }

    return res.status(201).json({
      id: this.lastID,
      name: cleanName,
      ingredients: cleanIngredients,
      instructions: cleanInstructions
    });
  });
});

app.listen(PORT, () => {
  console.log(`Recipe app running at http://localhost:${PORT}`);
});
