const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

let books = [
    { id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
    { id: 2, title: "1984", author: "George Orwell" }
];

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


app.get('/api/v1/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id);
    const book = books.find(b => b.id === bookId);

    if (!book) {
      
        return res.status(404).json({ message: "Book not found" });
    }

    res.status(200).json(book);
});


app.post('/api/v1/books', (req, res) => {
    const { title, author } = req.body;

    if (!title || !author) {
       
        return res.status(400).json({ message: "Title and Author are required" });
    }

    const newBook = {
        id: books.length + 1, 
        title,
        author
    };

    books.push(newBook);
    
   
    res.status(201).json(newBook);
});


app.put('/api/v1/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id);
    const { title, author } = req.body;
    
    const bookIndex = books.findIndex(b => b.id === bookId);

    if (bookIndex === -1) {
        return res.status(404).json({ message: "Book not found" });
    }

    // Replaces the entire resource
    books[bookIndex] = { id: bookId, title, author };

    res.status(200).json(books[bookIndex]);
});


app.delete('/api/v1/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id);
    const bookIndex = books.findIndex(b => b.id === bookId);

    if (bookIndex === -1) {
        return res.status(404).json({ message: "Book not found" });
    }


    const deletedBook = books.splice(bookIndex, 1);
    
    res.status(200).json({ message: "Book deleted successfully", book: deletedBook[0] });
});

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