"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addBlogComment = exports.deleteBlog = exports.updateBlog = exports.createBlog = exports.getBlogBySlug = exports.getBlogs = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
// 1. Get List of Published Blog Posts
const getBlogs = async (req, res) => {
    try {
        const { category, tag, search, status = 'PUBLISHED', limit = 10, page = 1 } = req.query;
        const take = Number(limit);
        const skip = (Number(page) - 1) * take;
        const where = {};
        if (status)
            where.status = String(status);
        if (category)
            where.category = String(category);
        if (search) {
            where.OR = [
                { title: { contains: String(search) } },
                { content: { contains: String(search) } },
            ];
        }
        const [blogs, total] = await Promise.all([
            database_1.default.blog.findMany({
                where,
                take,
                skip,
                include: {
                    _count: { select: { comments: true } },
                },
                orderBy: { publishedAt: 'desc' },
            }),
            database_1.default.blog.count({ where }),
        ]);
        return (0, response_utils_1.sendSuccess)(res, 'Blogs retrieved successfully', {
            blogs,
            pagination: {
                total,
                page: Number(page),
                limit: take,
                totalPages: Math.ceil(total / take),
            },
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error fetching blogs', error.message, 500);
    }
};
exports.getBlogs = getBlogs;
// 2. Get Single Blog Detail by Slug (Increments Views & Fetches Related Posts)
const getBlogBySlug = async (req, res) => {
    try {
        const { slug } = req.params;
        const blog = await database_1.default.blog.findUnique({
            where: { slug },
            include: {
                comments: {
                    where: { isApproved: true },
                    orderBy: { createdAt: 'desc' },
                },
            },
        });
        if (!blog) {
            return (0, response_utils_1.sendError)(res, 'Blog post not found', null, 404);
        }
        // Increment View Counter asynchronously
        await database_1.default.blog.update({
            where: { id: blog.id },
            data: { viewsCount: { increment: 1 } },
        }).catch(() => null);
        // Fetch 3 Related Blogs in Same Category
        const relatedBlogs = await database_1.default.blog.findMany({
            where: {
                category: blog.category,
                id: { not: blog.id },
                status: 'PUBLISHED',
            },
            take: 3,
            orderBy: { publishedAt: 'desc' },
        });
        // Social Share Links metadata generator
        const shareUrl = `${process.env.FRONTEND_URL || 'http://localhost:3000'}/blog/${blog.slug}`;
        const socialShares = {
            twitter: `https://twitter.com/intent/tweet?text=${encodeURIComponent(blog.title)}&url=${encodeURIComponent(shareUrl)}`,
            facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`,
            linkedin: `https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(blog.title)}`,
            whatsapp: `https://api.whatsapp.com/send?text=${encodeURIComponent(`${blog.title} - ${shareUrl}`)}`,
        };
        return (0, response_utils_1.sendSuccess)(res, 'Blog detail retrieved', {
            blog,
            relatedBlogs,
            socialShares,
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error fetching blog detail', error.message, 500);
    }
};
exports.getBlogBySlug = getBlogBySlug;
// 3. Create Blog Post (Admin)
const createBlog = async (req, res) => {
    try {
        const { title, slug, content, excerpt, coverImage, authorName = 'IBW Editorial', authorAvatar, category = 'Literary News', tags = [], status = 'PUBLISHED', metaTitle, metaDescription, publishedAt, } = req.body;
        const generatedSlug = slug || title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '');
        const blog = await database_1.default.blog.create({
            data: {
                title,
                slug: generatedSlug,
                content,
                excerpt: excerpt || content.substring(0, 150),
                coverImage,
                authorName,
                authorAvatar,
                category,
                tags,
                status: status,
                metaTitle: metaTitle || title,
                metaDescription: metaDescription || excerpt || content.substring(0, 160),
                publishedAt: publishedAt ? new Date(publishedAt) : new Date(),
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Blog post created successfully', blog, 201);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error creating blog post', error.message, 500);
    }
};
exports.createBlog = createBlog;
// 4. Update Blog Post (Admin)
const updateBlog = async (req, res) => {
    try {
        const { id } = req.params;
        const updateData = req.body;
        const updatedBlog = await database_1.default.blog.update({
            where: { id },
            data: updateData,
        });
        return (0, response_utils_1.sendSuccess)(res, 'Blog post updated successfully', updatedBlog);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error updating blog post', error.message, 500);
    }
};
exports.updateBlog = updateBlog;
// 5. Delete Blog Post (Admin)
const deleteBlog = async (req, res) => {
    try {
        const { id } = req.params;
        await database_1.default.blog.delete({ where: { id } });
        return (0, response_utils_1.sendSuccess)(res, 'Blog post deleted successfully');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error deleting blog post', error.message, 500);
    }
};
exports.deleteBlog = deleteBlog;
// 6. Post Comment on Blog
const addBlogComment = async (req, res) => {
    try {
        const { blogId, authorName, content } = req.body;
        const userId = req.user?.userId;
        const comment = await database_1.default.blogComment.create({
            data: {
                blogId,
                userId,
                authorName,
                content,
                isApproved: true,
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Comment published successfully', comment, 201);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to post comment', error.message, 500);
    }
};
exports.addBlogComment = addBlogComment;
//# sourceMappingURL=blog.controller.js.map