/**
 * Blogger Posts API Routes
 *
 * Blogger-specific publication jobs. Mounted at /api/blogger/posts.
 * Follows the same pattern as facebookPublications, instagramPublications, etc.
 *
 * - GET    /               → list publications (company-scoped, platform=blogger)
 * - GET    /detail/:id      → single publication
 * - POST   /               → create a publication (draft | publish now | scheduled)
 * - PUT    /:id             → edit metadata (draft/failed locally)
 * - POST   /:id/publish    → queue a draft/failed/cancelled publication for publishing
 * - POST   /:id/cancel     → cancel a queued/scheduled publication
 * - DELETE /:id             → remove a draft/failed/cancelled record
 *
 * Publishing isolation: a publication can only target a blog owned by the
 * requesting admin, and only its creator can mutate it.
 */

import express, { Request, Response } from 'express';
import { authenticate } from '../middleware/auth';
import { requirePermission } from '../middleware/permissions';
import { getModels } from '../models';
import {
  createPost,
  deletePost as deleteBloggerPost,
  revertPost,
  listPosts as listBloggerPosts,
  listBlogs,
} from '../services/blogger/bloggerApi';

const router = express.Router();

router.use(authenticate);

// ============================================
// HELPERS
// ============================================

const authorizeCompany = (req: Request, companyId: string): boolean => {
  return req.user!.companyIds.includes(companyId) || req.user!.role === 'admin';
};

const handleError = (res: Response, error: any) => {
  if (error.name === 'ValidationError') {
    res.status(400).json({ error: error.message, details: Object.values(error.errors || {}).map((e: any) => e.message) });
    return;
  }
  res.status(500).json({ error: error.message });
};

/**
 * Validate a Blogger publication payload.
 * Returns an error string or null.
 */
function validateBloggerPayload(body: any): string | null {
  const title = String(body.title || '').trim();
  if (!title) return 'Title is required';
  if (title.length > 200) return 'Blogger post titles are limited to 200 characters';

  // content is optional for drafts but required for publishing
  if (!body.isDraft && !body.content && !body.contentHtml) {
    return 'Content is required when publishing immediately';
  }

  if (body.labels && !Array.isArray(body.labels)) {
    return 'Labels must be an array of strings';
  }

  if (body.labels && body.labels.length > 20) {
    return 'Maximum 20 labels per post';
  }

  return null;
}

/**
 * Load a publication and verify the requester created it.
 */
async function loadOwnedPublication(req: Request, res: Response, id: string): Promise<any | null> {
  const { SocialMediaPublication } = getModels();
  const publication = await (SocialMediaPublication as any).findById(id);

  if (!publication) {
    res.status(404).json({ error: 'Publication not found' });
    return null;
  }
  if (!authorizeCompany(req, publication.companyId)) {
    res.status(403).json({ error: 'Access denied' });
    return null;
  }
  if (publication.createdBy !== req.user!._id.toString()) {
    res.status(403).json({ error: 'Only the admin who created this publication can manage it' });
    return null;
  }
  return publication;
}

// ============================================
// DASHBOARD — aggregated stats for the Blogger dashboard UI
// ============================================

router.get('/dashboard', async (req: Request, res: Response) => {
  try {
    const userId = req.user!._id.toString();
    const companyId = req.query.companyId as string || req.user!.activeCompanyId || req.user!.companyIds[0];

    if (!companyId || !authorizeCompany(req, companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const { BloggerAccount, SocialMediaPublication } = getModels();

    // Find the admin's connected Blogger account
    const account = await (BloggerAccount as any).findOne({ companyId, userId, status: 'connected' });

    if (!account) {
      res.json({
        connected: false,
        account: null,
        stats: { totalPosts: 0, publishedPosts: 0, draftPosts: 0, scheduledPosts: 0, failedPosts: 0 },
        recentPublications: [],
      });
      return;
    }

    // Aggregate publication counts by status
    const statusCounts = await (SocialMediaPublication as any).aggregate([
      { $match: { companyId, platform: 'blogger' } },
      { $group: { _id: '$status', count: { $sum: 1 } } },
    ]);

    const stats: Record<string, number> = {
      totalPosts: 0,
      publishedPosts: 0,
      draftPosts: 0,
      scheduledPosts: 0,
      failedPosts: 0,
    };

    for (const entry of statusCounts) {
      stats.totalPosts += entry.count;
      switch (entry._id) {
        case 'published': stats.publishedPosts = entry.count; break;
        case 'draft': stats.draftPosts = entry.count; break;
        case 'scheduled': stats.scheduledPosts = entry.count; break;
        case 'failed': stats.failedPosts = entry.count; break;
      }
    }

    // Get recent publications (last 10)
    const recentPublications = await (SocialMediaPublication as any)
      .find({ companyId, platform: 'blogger' })
      .sort({ createdAt: -1 })
      .limit(10)
      .select('-__v')
      .lean();

    res.json({
      connected: true,
      account: {
        id: account._id.toString(),
        googleUserName: account.googleUserName,
        googleUserEmail: account.googleUserEmail,
        googleUserPicture: account.googleUserPicture,
        defaultBlogId: account.defaultBlogId,
        defaultBlogName: account.defaultBlogName,
        defaultBlogUrl: account.defaultBlogUrl,
        availableBlogs: account.availableBlogs,
        status: account.status,
        connectedAt: account.connectedAt,
        lastUsedAt: account.lastUsedAt,
        lastSyncedAt: account.lastSyncedAt,
      },
      stats,
      recentPublications,
    });
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// SYNC — import posts from Blogger into local DB
// ============================================

router.post('/sync', async (req: Request, res: Response) => {
  try {
    const userId = req.user!._id.toString();
    const companyId = req.body.companyId || req.user!.activeCompanyId || req.user!.companyIds[0];
    const { accountId, blogId } = req.body;

    if (!companyId || !authorizeCompany(req, companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    if (!accountId || !blogId) {
      res.status(400).json({ error: 'accountId and blogId are required' });
      return;
    }

    const { BloggerAccount, SocialMediaPublication } = getModels();

    // Verify the account belongs to this admin
    const account = await (BloggerAccount as any).findOne({
      _id: accountId,
      companyId,
      userId,
      status: 'connected',
    });

    if (!account) {
      res.status(403).json({ error: 'Connected Blogger account not found. Please reconnect.' });
      return;
    }

    // Fetch all posts from Blogger (drafts, live, and scheduled)
    const result = await listBloggerPosts(companyId, userId, accountId, blogId, {
      status: 'live',
      maxResults: 500,
      fetchBodies: true,
    });

    if (result.error) {
      res.status(502).json({ error: `Failed to fetch posts from Blogger: ${result.error}` });
      return;
    }

    // Also fetch drafts and scheduled posts
    const [draftResult, scheduledResult] = await Promise.all([
      listBloggerPosts(companyId, userId, accountId, blogId, {
        status: 'draft',
        maxResults: 500,
        fetchBodies: true,
      }),
      listBloggerPosts(companyId, userId, accountId, blogId, {
        status: 'scheduled',
        maxResults: 500,
        fetchBodies: true,
      }),
    ]);

    const allPosts = [
      ...(result.posts || []),
      ...(draftResult.posts || []),
      ...(scheduledResult.posts || []),
    ];

    let created = 0;
    let updated = 0;
    const errors: string[] = [];

    for (const post of allPosts) {
      try {
        // Check if we already have this post locally
        const existing = await (SocialMediaPublication as any).findOne({
          companyId,
          platform: 'blogger',
          bloggerPostId: post.id,
        });

        // Map Blogger status to our status
        const bloggerStatus = (post.status || '').toUpperCase();
        let ourStatus: string;
        switch (bloggerStatus) {
          case 'LIVE': ourStatus = 'published'; break;
          case 'DRAFT': ourStatus = 'draft'; break;
          case 'SCHEDULED': ourStatus = 'scheduled'; break;
          default: ourStatus = 'published'; break;
        }

        const postData = {
          title: post.title || '',
          description: post.content || '',
          bloggerLabels: post.labels || [],
          bloggerPostUrl: post.url || '',
          platformPostId: post.id,
          platformUrl: post.url || '',
          status: ourStatus,
          publishedAt: post.published ? new Date(post.published) : undefined,
        };

        if (existing) {
          // Update existing record
          Object.assign(existing, postData);
          existing.updatedAt = new Date();
          await existing.save();
          updated++;
        } else {
          // Create new record
          const publication = new (SocialMediaPublication as any)({
            companyId,
            createdBy: userId,
            platform: 'blogger',
            accountRef: accountId,
            channelId: blogId,
            channelTitle: account.defaultBlogName || '',
            blogId,
            blogName: account.defaultBlogName || '',
            blogUrl: account.defaultBlogUrl || '',
            bloggerPostId: post.id,
            bloggerIsDraft: bloggerStatus === 'DRAFT',
            ...postData,
          });
          await publication.save();
          created++;
        }
      } catch (err: any) {
        errors.push(`Post "${post.title || post.id}": ${err.message}`);
      }
    }

    // Update lastSyncedAt on the account
    account.lastSyncedAt = new Date();
    await account.save();

    res.json({
      synced: allPosts.length,
      created,
      updated,
      errors: errors.length > 0 ? errors : undefined,
    });
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// CREATE — queue a Blogger publication
// ============================================

router.post('/', requirePermission('social-media-os', 'create'), async (req: Request, res: Response) => {
  try {
    const userId = req.user!._id.toString();
    const companyId = req.body.companyId || req.user!.activeCompanyId || req.user!.companyIds[0];

    if (!companyId || !authorizeCompany(req, companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const validationError = validateBloggerPayload(req.body);
    if (validationError) {
      res.status(400).json({ error: validationError });
      return;
    }

    // The target blog must belong to one of the admin's connected Blogger accounts
    const { BloggerAccount, SocialMediaPublication } = getModels();
    const account = await (BloggerAccount as any).findOne({
      _id: req.body.accountId,
      companyId,
      userId,
      status: 'connected',
    });

    if (!account) {
      res.status(403).json({ error: 'Blog account not found among your connected Blogger accounts. You can only publish through accounts you connected yourself.' });
      return;
    }

    const action = req.body.isDraft ? 'draft' : 'queued';
    const blogId = req.body.blogId || account.defaultBlogId;

    if (!blogId) {
      res.status(400).json({ error: 'A blog ID is required. Please select a blog to publish to.' });
      return;
    }

    // Resolve blog name from available blogs on the account
    const blogInfo = (account.availableBlogs || []).find((b: any) => b.blogId === blogId);
    const blogName = blogInfo?.blogName || account.defaultBlogName || '';
    const blogUrl = blogInfo?.blogUrl || account.defaultBlogUrl || '';

    const content = req.body.content || req.body.contentHtml || '';
    const labels = Array.isArray(req.body.labels) ? req.body.labels : [];

    const publication = new (SocialMediaPublication as any)({
      companyId,
      createdBy: userId,
      platform: 'blogger',
      accountRef: account._id.toString(),
      channelId: blogId,         // reuse channelId for blogId (generic target field)
      channelTitle: blogName,    // reuse channelTitle for blogName
      campaignId: req.body.campaignId || null,
      contentRef: req.body.contentRef || null,
      title: String(req.body.title).trim(),
      description: content,
      // Blogger-specific fields
      blogId,
      blogName,
      blogUrl,
      bloggerLabels: labels,
      bloggerIsDraft: !!req.body.isDraft,
      bloggerPublishDate: req.body.publishAt || null,
      publishAt: req.body.publishAt ? new Date(req.body.publishAt) : null,
      status: action,
    });

    await publication.save();

    // If not a draft, attempt immediate publishing to Blogger
    if (action === 'queued') {
      try {
        const accountId = account._id.toString();
        const postResult = await createPost(companyId, userId, accountId, blogId, {
          title: publication.title,
          content,
          labels: labels.length > 0 ? labels : undefined,
          isDraft: false,
        });

        if (postResult.error) {
          publication.status = 'failed';
          publication.lastError = { code: 'BLOGGER_API_ERROR', message: postResult.error, at: new Date() };
          publication.errorHistory = [...(publication.errorHistory || []), publication.lastError];
          await publication.save();

          res.status(502).json({ error: `Failed to publish to Blogger: ${postResult.error}`, publication });
          return;
        }

        // Success
        publication.status = 'published';
        publication.bloggerPostId = postResult.post?.id || null;
        publication.bloggerPostUrl = postResult.post?.url || null;
        publication.platformPostId = postResult.post?.id || null;
        publication.platformUrl = postResult.post?.url || null;
        publication.publishedAt = new Date();
        await publication.save();
      } catch (publishError: any) {
        publication.status = 'failed';
        publication.lastError = { code: 'PUBLISH_EXCEPTION', message: publishError.message, at: new Date() };
        publication.errorHistory = [...(publication.errorHistory || []), publication.lastError];
        await publication.save();

        res.status(502).json({ error: `Failed to publish to Blogger: ${publishError.message}`, publication });
        return;
      }
    }

    res.status(201).json(publication);
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// READ — list and detail
// ============================================

router.get('/', async (req: Request, res: Response) => {
  try {
    const companyId = req.query.companyId as string || req.user!.activeCompanyId || req.user!.companyIds[0];
    if (!companyId || !authorizeCompany(req, companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const { SocialMediaPublication } = getModels();
    const filter: Record<string, unknown> = { companyId, platform: 'blogger' };
    if (req.query.campaignId) filter.campaignId = String(req.query.campaignId);
    if (req.query.status) filter.status = String(req.query.status);

    const publications = await (SocialMediaPublication as any).find(filter).sort({ createdAt: -1 }).limit(200);
    res.json(publications);
  } catch (error: any) {
    handleError(res, error);
  }
});

router.get('/detail/:id', async (req: Request, res: Response) => {
  try {
    const { SocialMediaPublication } = getModels();
    const publication = await (SocialMediaPublication as any).findById(req.params.id);
    if (!publication) {
      res.status(404).json({ error: 'Publication not found' });
      return;
    }
    if (!authorizeCompany(req, publication.companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }
    res.json(publication);
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// UPDATE — edit a draft/failed publication
// ============================================

router.put('/:id', requirePermission('social-media-os', 'edit'), async (req: Request, res: Response) => {
  try {
    const publication = await loadOwnedPublication(req, res, req.params.id);
    if (!publication) return;

    if (!['draft', 'failed'].includes(publication.status)) {
      res.status(400).json({ error: `A publication in "${publication.status}" state cannot be edited` });
      return;
    }

    // Update allowed fields
    const editable = ['title', 'description', 'bloggerLabels', 'blogId', 'bloggerIsDraft', 'bloggerPublishDate', 'publishAt'];
    for (const key of editable) {
      if (req.body[key] !== undefined) {
        if (key === 'publishAt' && req.body[key]) {
          publication[key] = new Date(req.body[key]);
        } else if (key === 'bloggerPublishDate' && req.body[key]) {
          publication[key] = req.body[key];
        } else {
          publication[key] = req.body[key];
        }
      }
    }

    // If blogId changed, update blogName and blogUrl from account's available blogs
    if (req.body.blogId && req.body.blogId !== publication.blogId) {
      const { BloggerAccount } = getModels();
      const account = await (BloggerAccount as any).findOne({
        _id: publication.accountRef,
        companyId: publication.companyId,
        userId: publication.createdBy,
        status: 'connected',
      });
      if (account) {
        const blogInfo = (account.availableBlogs || []).find((b: any) => b.blogId === req.body.blogId);
        if (blogInfo) {
          publication.blogName = blogInfo.blogName;
          publication.blogUrl = blogInfo.blogUrl;
        }
      }
    }

    // If re-submitting for publishing, re-queue
    if (publication.status === 'failed' && req.body.action !== 'draft') {
      publication.status = 'queued';
      publication.attemptCount = 0;
      publication.nextAttemptAt = null;
      publication.workerLockedAt = null;
      publication.lastError = null;
    }

    await publication.save();
    res.json(publication);
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// UPDATE ON BLOGGER — push local edits to the live Blogger post
// ============================================

router.put('/:id/update-blogger', requirePermission('social-media-os', 'edit'), async (req: Request, res: Response) => {
  try {
    const publication = await loadOwnedPublication(req, res, req.params.id);
    if (!publication) return;

    // Must have a Blogger post ID to update on Blogger
    if (!publication.bloggerPostId) {
      res.status(400).json({ error: 'This publication has not been published to Blogger yet. Use the publish endpoint instead.' });
      return;
    }

    const blogId = publication.blogId || publication.channelId;
    if (!blogId) {
      res.status(400).json({ error: 'No blog ID associated with this publication.' });
      return;
    }

    // Verify the account is connected
    const { BloggerAccount } = getModels();
    const account = await (BloggerAccount as any).findOne({
      _id: publication.accountRef,
      companyId: publication.companyId,
      userId: publication.createdBy,
      status: 'connected',
    });

    if (!account) {
      res.status(400).json({ error: 'Connected Blogger account not found. Please reconnect.' });
      return;
    }

    const accountId = account._id.toString();
    const { updatePost } = await import('../services/blogger/bloggerApi');

    // Build update data from request body or existing publication
    const updateData: any = {};
    if (req.body.title !== undefined) updateData.title = String(req.body.title).trim();
    if (req.body.content !== undefined) updateData.content = req.body.content;
    if (req.body.labels !== undefined) {
      if (!Array.isArray(req.body.labels)) {
        res.status(400).json({ error: 'Labels must be an array of strings' });
        return;
      }
      updateData.labels = req.body.labels;
    }

    // If no fields provided, use existing publication data
    if (Object.keys(updateData).length === 0) {
      updateData.title = publication.title;
      updateData.content = publication.description || '';
      updateData.labels = publication.bloggerLabels || [];
    }

    const postResult = await updatePost(
      publication.companyId,
      publication.createdBy,
      accountId,
      blogId,
      publication.bloggerPostId,
      updateData
    );

    if (postResult.error) {
      res.status(502).json({ error: `Failed to update post on Blogger: ${postResult.error}` });
      return;
    }

    // Update local record with Blogger response
    if (postResult.post) {
      publication.title = postResult.post.title || publication.title;
      publication.description = postResult.post.content || publication.description;
      publication.bloggerPostUrl = postResult.post.url || publication.bloggerPostUrl;
      publication.platformUrl = postResult.post.url || publication.platformUrl;
      publication.bloggerLabels = postResult.post.labels || publication.bloggerLabels;
    }
    publication.lastError = null;
    await publication.save();

    res.json(publication);
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// PUBLISH / RETRY — queue a draft/failed/cancelled publication
// ============================================

router.post('/:id/publish', requirePermission('social-media-os', 'edit'), async (req: Request, res: Response) => {
  try {
    const publication = await loadOwnedPublication(req, res, req.params.id);
    if (!publication) return;

    if (!['draft', 'failed', 'cancelled'].includes(publication.status)) {
      res.status(400).json({ error: `A publication in "${publication.status}" state cannot be queued` });
      return;
    }

    // Attempt to publish to Blogger immediately
    const { BloggerAccount } = getModels();
    const account = await (BloggerAccount as any).findOne({
      _id: publication.accountRef,
      companyId: publication.companyId,
      userId: publication.createdBy,
      status: 'connected',
    });

    if (!account) {
      res.status(400).json({ error: 'Connected Blogger account not found. Please reconnect.' });
      return;
    }

    const blogId = publication.blogId || account.defaultBlogId;
    if (!blogId) {
      res.status(400).json({ error: 'No blog selected for this publication.' });
      return;
    }

    const accountId = account._id.toString();

    // If scheduled for the future, just queue it
    if (publication.publishAt && new Date(publication.publishAt) > new Date()) {
      publication.status = 'scheduled';
      publication.attemptCount = 0;
      publication.lastError = null;
      await publication.save();
      res.json(publication);
      return;
    }

    // Publish now
    try {
      const postResult = await createPost(
        publication.companyId,
        publication.createdBy,
        accountId,
        blogId,
        {
          title: publication.title,
          content: publication.description || '',
          labels: publication.bloggerLabels?.length > 0 ? publication.bloggerLabels : undefined,
          isDraft: publication.bloggerIsDraft || false,
        }
      );

      if (postResult.error) {
        publication.status = 'failed';
        publication.lastError = { code: 'BLOGGER_API_ERROR', message: postResult.error, at: new Date() };
        publication.errorHistory = [...(publication.errorHistory || []), publication.lastError];
        publication.attemptCount = (publication.attemptCount || 0) + 1;
        await publication.save();
        res.status(502).json({ error: `Failed to publish to Blogger: ${postResult.error}`, publication });
        return;
      }

      publication.status = 'published';
      publication.bloggerPostId = postResult.post?.id || null;
      publication.bloggerPostUrl = postResult.post?.url || null;
      publication.platformPostId = postResult.post?.id || null;
      publication.platformUrl = postResult.post?.url || null;
      publication.publishedAt = new Date();
      publication.lastError = null;
      await publication.save();
      res.json(publication);
    } catch (publishError: any) {
      publication.status = 'failed';
      publication.lastError = { code: 'PUBLISH_EXCEPTION', message: publishError.message, at: new Date() };
      publication.errorHistory = [...(publication.errorHistory || []), publication.lastError];
      publication.attemptCount = (publication.attemptCount || 0) + 1;
      await publication.save();
      res.status(502).json({ error: `Failed to publish to Blogger: ${publishError.message}` });
    }
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// CANCEL — cancel a queued/scheduled publication
// ============================================

router.post('/:id/cancel', requirePermission('social-media-os', 'edit'), async (req: Request, res: Response) => {
  try {
    const publication = await loadOwnedPublication(req, res, req.params.id);
    if (!publication) return;

    if (!['draft', 'queued', 'scheduled'].includes(publication.status)) {
      res.status(400).json({ error: `A publication in "${publication.status}" state cannot be cancelled` });
      return;
    }

    // If already published on Blogger, attempt to revert it to draft
    if (publication.bloggerPostId && publication.blogId) {
      try {
        const { BloggerAccount } = getModels();
        const account = await (BloggerAccount as any).findOne({
          _id: publication.accountRef,
          companyId: publication.companyId,
          userId: publication.createdBy,
          status: 'connected',
        });

        if (account) {
          await revertPost(publication.companyId, publication.createdBy, account._id.toString(), publication.blogId, publication.bloggerPostId);
        }
      } catch (e) {
        // Best-effort — don't fail the cancel if Blogger revert fails
        console.warn('[Blogger] Failed to revert post on Blogger during cancel:', e);
      }
    }

    publication.status = 'cancelled';
    publication.workerLockedAt = null;
    await publication.save();

    res.json(publication);
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// DELETE — remove a draft/failed/cancelled record
// ============================================

router.delete('/:id', requirePermission('social-media-os', 'delete'), async (req: Request, res: Response) => {
  try {
    const publication = await loadOwnedPublication(req, res, req.params.id);
    if (!publication) return;

    if (!['draft', 'failed', 'cancelled'].includes(publication.status)) {
      res.status(400).json({ error: 'Only draft, failed, or cancelled publications can be deleted' });
      return;
    }

    // If the post was published on Blogger, attempt to delete it there too
    if (publication.bloggerPostId && publication.blogId) {
      try {
        const { BloggerAccount } = getModels();
        const account = await (BloggerAccount as any).findOne({
          _id: publication.accountRef,
          companyId: publication.companyId,
          userId: publication.createdBy,
          status: 'connected',
        });

        if (account) {
          await deleteBloggerPost(publication.companyId, publication.createdBy, account._id.toString(), publication.blogId, publication.bloggerPostId);
        }
      } catch (e) {
        // Best-effort — don't fail the local delete if Blogger delete fails
        console.warn('[Blogger] Failed to delete post on Blogger:', e);
      }
    }

    await publication.deleteOne();
    res.json({ message: 'Publication deleted' });
  } catch (error: any) {
    handleError(res, error);
  }
});

// ============================================
// LIVE BLOGGER API PROXIES — fetch live data from Blogger
// ============================================

/**
 * GET /blogs — list the user's blogs from Blogger API
 * Uses the connected account to fetch live blog list.
 */
router.get('/blogs', async (req: Request, res: Response) => {
  try {
    const userId = req.user!._id.toString();
    const companyId = req.query.companyId as string || req.user!.activeCompanyId || req.user!.companyIds[0];

    if (!companyId || !authorizeCompany(req, companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const accountId = req.query.accountId as string;
    if (!accountId) {
      res.status(400).json({ error: 'accountId query parameter is required' });
      return;
    }

    const result = await listBlogs(companyId, userId, accountId);
    if (result.error) {
      res.status(502).json({ error: result.error });
      return;
    }

    res.json({ blogs: result.blogs });
  } catch (error: any) {
    handleError(res, error);
  }
});

/**
 * GET /posts — list posts from a specific blog via Blogger API
 */
router.get('/posts', async (req: Request, res: Response) => {
  try {
    const userId = req.user!._id.toString();
    const companyId = req.query.companyId as string || req.user!.activeCompanyId || req.user!.companyIds[0];

    if (!companyId || !authorizeCompany(req, companyId)) {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const accountId = req.query.accountId as string;
    const blogId = req.query.blogId as string;

    if (!accountId || !blogId) {
      res.status(400).json({ error: 'accountId and blogId query parameters are required' });
      return;
    }

    const options: any = {};
    if (req.query.maxResults) options.maxResults = parseInt(req.query.maxResults as string, 10);
    if (req.query.pageToken) options.pageToken = req.query.pageToken as string;
    if (req.query.status) options.status = req.query.status as string;
    if (req.query.labels) options.labels = req.query.labels as string;
    if (req.query.fetchBodies) options.fetchBodies = req.query.fetchBodies === 'true';
    if (req.query.orderBy) options.orderBy = req.query.orderBy as string;

    const result = await listBloggerPosts(companyId, userId, accountId, blogId, options);
    if (result.error) {
      res.status(502).json({ error: result.error });
      return;
    }

    res.json({ posts: result.posts, nextPageToken: result.nextPageToken });
  } catch (error: any) {
    handleError(res, error);
  }
});

export default router;