import express from 'express';
import multer from 'multer';
import cors from 'cors';
import path from 'path';
import crypto from 'crypto';

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, path.join(import.meta.dirname, '..', 'public'));
  },
  filename(req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, crypto.randomUUID() + ext);
  },
});

const upload = multer({ storage });

const app = express();
app.use(express.json());
app.use(cors());

const books = [
  {
    id: 1,
    title: 'JavaScript - das umfassende Handbuch',
  },
  {
    id: 2,
    title: 'Clean Code',
  },
  {
    id: 3,
    title: 'Design Patterns',
  },
];

app.get('/books', (req, res) => {
  res.json(books);
});

app.post('/books', upload.single('image'), (req, res) => {
  const book = {
    id: Math.max(...books.map((b) => b.id)) + 1,
    title: req.body.title,
    image: req.file.filename,
  };
  books.push(book);
  res.status(201).json(book);
});

const PORT = 3001;
app.listen(PORT, () =>
  console.log(`Server listening on http://localhost:${PORT}`)
);
