import libraryService from "../services/libraryService.js";
import { ApiError, asyncHandler } from "../utils/helpers.js";

export const addBook = asyncHandler(async (req, res) => {
    if (req.role !== "librarian") {
        throw new ApiError(403, "Forbidden");
    }

    const { title, author, description } = req.body;
    if (!title || !author || !description) {
        throw new ApiError(400, "Missing required fields");
    }

    await libraryService.addBook(title, author, description);
    res.status(201).json({ message: "Book added successfully" });
});

export const updateBook = asyncHandler(async (req, res) => {
    if (req.role !== "librarian") {
        throw new ApiError(403, "Forbidden");
    }

    const { title, author, description } = req.body;
    if (!title || !author || !description) {
        throw new ApiError(400, "Missing required fields");
    }

    await libraryService.updateBook(req.params.id, title, author, description);
    res.status(200).json({ message: "Book updated successfully" });
});

export const deleteBook = asyncHandler(async (req, res) => {
    await libraryService.deleteBook(req.params.id);
    res.status(200).json({ message: "Book deleted successfully" });
});

export const getAllBooks = asyncHandler(async (req, res) => {
    const books = await libraryService.getAllBooks();
    res.status(200).json(books);
});