import { Router } from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import multer from 'multer';
import { createBlog, updateBlog, listBlogs, getBlog, createPost, listPosts, listBlogImages, uploadBlogImage, getPublicBlogImageByHash, shareBlog, resolveBlogSlug, resolveBlogSlugId } from '../controllers/blogController.js';

const upload = multer();

const router = Router();

// Public list (filtered by visibility); if logged in, pass userid in headers for access
router.get('/blogs', listBlogs);
// Public get (access enforced per blog)
router.get('/blogs/:id', getBlog);
// Public list posts (access enforced per blog)
router.get('/blogs/:id/posts', listPosts); // supports ?page=&pageSize=
// Public serve image by hash if folder has 'everyone' visibility
router.get('/blogs/images/:hash', getPublicBlogImageByHash);
// Public: resolve pretty slug to SPA route and JSON id
router.get('/blogs/slug/:slug', resolveBlogSlug);
router.get('/blogs/slug/:slug/id', resolveBlogSlugId);

// Create/Update require login (any logged-in user can create/edit their own blog); posts require login
router.post('/blogs', authenticate, createBlog);
router.put('/blogs/:id', authenticate, updateBlog);
router.post('/blogs/:id/posts', authenticate, createPost);
router.post('/blogs/:id/share', authenticate, shareBlog);

// Blog images: list and upload to user's Blog folder
router.get('/blogs/:id/images', authenticate, listBlogImages);
router.post('/blogs/:id/images', authenticate, upload.single('image'), uploadBlogImage);

export default router;
