/**
 * Case Studies AI Context Routes
 *
 * API endpoints for Case Study AI generation.
 * POST /auto-fill — generate multiple case studies from company context
 * POST /regenerate — regenerate case study data using existing context
 */

import express, { Request, Response } from 'express';
import { body, validationResult } from 'express-validator';
import { authenticate } from '../middleware/auth';
import { requirePermission } from '../middleware/permissions';
import { CaseStudyPipeline } from '../services/aiContext/caseStudyPipeline';
import { CaseStudyPipelineInputs } from '../services/aiContext/caseStudyPrompts';
import { aiContextService, computeCaseStudyAutoFillMapping } from '../services/aiContext/aiContextService';
import { getModels } from '../models';
import { createJob, updateJobProgress, completeJob, failJob, getJob, setJobMetadata } from '../services/aiContext/aiJobManager';

const router = express.Router();
router.use(authenticate);

router.get(
  '/status/:jobId',
  async (req: Request, res: Response) => {
    const { jobId } = req.params;
    const job = getJob(jobId);

    if (!job) {
      res.status(404).json({ error: 'Job not found' });
      return;
    }

    res.json({
      jobId: job.jobId,
      status: job.status,
      progress: job.progress,
      step: job.step,
      result: job.result,
      error: job.error,
      // Provider/model/token details as captured so far, so the AI Processing
      // screen can render live values instead of placeholders mid-generation.
      metadata: job.metadata,
    });
  }
);

// ============================================
// POST /auto-fill
// ============================================

router.post(
  '/auto-fill',
  requirePermission('case-studies', 'ai-generate'),
  [
    body('companyId').notEmpty().withMessage('Company ID is required'),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({ error: 'Validation failed', details: errors.array() });
      return;
    }

    const { companyId, targetCount, description, customInstructions } = req.body;
    const count = Math.min(Math.max(Number(targetCount) || 1, 1), 6);
    const language = req.body.language || 'English';

    // Start async generation
    const job = createJob('case-studies', companyId, req.body._moduleId);

    // Return jobId immediately so the frontend can poll
    res.status(202).json({ jobId: job.jobId, status: 'processing' });

    // Run pipeline in background (do NOT await on the response path)
    setImmediate(async () => {
      try {
        const { Company, BusinessProfile, ICP } = getModels();
        const company = await Company.findById(companyId);
        if (!company) {
          failJob(job.jobId, 'Company not found');
          return;
        }

        let businessProfile: any = null;
        try { businessProfile = await BusinessProfile.findOne({ companyId }); } catch {}

        const companyContexts = await aiContextService.getByCompany(companyId, 'company-creation');
        const latestCompanyContext = companyContexts.find((c: any) => {
          const a = c.analysis?.toObject?.() || c.analysis || {};
          return c.status === 'approved' || a.industryType || a.businessModel || a.businessSummary;
        });

        let icpData: any = null;
        try { icpData = await ICP.findOne({ companyId, isActive: true }).sort({ createdAt: -1 }); } catch {}

        // Load brand strategy context for enrichment
        let brandStrategyData: any = null;
        try {
          const { ModuleData } = getModels();
          const brandStrategyDoc = await ModuleData.findOne({ moduleId: 'brand-strategy', companyId });
          if (brandStrategyDoc?.data) {
            brandStrategyData = brandStrategyDoc.data;
          }
        } catch {}

        // Build pipeline inputs
        const pipelineInputs: CaseStudyPipelineInputs = {
          // The user's own brief from the "Generate with AI" popup or the AI Chat
          // generation flow. Stated as the highest-priority instruction in the
          // prompt, so it wins over the derived company context.
          customInstructions:
            typeof customInstructions === 'string' && customInstructions.trim()
              ? customInstructions.trim()
              : undefined,
          companyName: company.name,
          companyDescription: company.description || businessProfile?.description || undefined,
          companyIndustry: businessProfile?.primaryIndustry || undefined,
          companyBusinessModel: businessProfile?.businessModel || undefined,
          companyTargetAudience: undefined,
          companyPrimaryOffering: undefined,
          companyUsps: undefined,
          targetCount: count,
          customDescription: description || undefined,
          language,
        };

        if (latestCompanyContext) {
          const analysis = (latestCompanyContext as any).analysis?.toObject?.() || (latestCompanyContext as any).analysis || {};
          if (analysis.industryType && !pipelineInputs.companyIndustry) pipelineInputs.companyIndustry = analysis.industryType;
          if (analysis.businessModel && !pipelineInputs.companyBusinessModel) pipelineInputs.companyBusinessModel = analysis.businessModel;
          if (analysis.targetAudience?.primary) pipelineInputs.companyTargetAudience = analysis.targetAudience.primary;
          if (analysis.primaryOffering) pipelineInputs.companyPrimaryOffering = analysis.primaryOffering;
          if (analysis.uspSuggestions?.length) pipelineInputs.companyUsps = analysis.uspSuggestions;
        }

        if (icpData) {
          pipelineInputs.icpName = icpData.name || undefined;
          pipelineInputs.icpIndustry = icpData.industry || undefined;
          pipelineInputs.icpPainPoints = icpData.painPoints || undefined;
          pipelineInputs.icpBusinessGoals = icpData.businessGoals || undefined;
        }

        if (brandStrategyData) {
          pipelineInputs.brandArchetype = brandStrategyData.brandArchetype || undefined;
          pipelineInputs.brandPersonality = brandStrategyData.brandPersonality || undefined;
          pipelineInputs.brandValues = brandStrategyData.brandValues || undefined;
          pipelineInputs.brandPositioning = brandStrategyData.brandPositioning || undefined;
          pipelineInputs.brandVoice = brandStrategyData.brandVoice || undefined;
        }

        updateJobProgress(job.jobId, 10, 'Preparing context...');
        const pipeline = new CaseStudyPipeline(pipelineInputs, (progress, step) => {
          updateJobProgress(job.jobId, progress, step);
          setJobMetadata(job.jobId, pipeline.getLiveMetadata());
        });
        const result = await pipeline.run();

        // Map each case study through the auto-fill mapping function
        const autoFillDataArray = result.caseStudies.map((csAnalysis: Record<string, any>) =>
          computeCaseStudyAutoFillMapping(csAnalysis)
        ).filter((data: Record<string, any>) => data.title); // Filter out any empty results

        console.log(`[CaseStudy-AutoFill] Generated ${autoFillDataArray.length} case studies`);

        // Create an AiContext record with the combined analysis
        const combinedAnalysis: Record<string, any> = {
          caseStudies: result.caseStudies,
          pipelineVersion: result.pipelineVersion,
          provider: result.provider,
          aiModel: result.aiModel,
          tokensUsed: result.tokensUsed,
          inputTokens: result.inputTokens,
          outputTokens: result.outputTokens,
          processingTimeMs: result.processingTimeMs,
          overallConfidence: result.overallConfidence,
          latencyMs: result.latencyMs,
        };

        const context = await aiContextService.create({
          companyId,
          moduleSource: 'case-studies',
          analysisType: 'full-analysis',
          inputs: { companyName: company.name, description: pipelineInputs.companyDescription } as any,
          analysis: combinedAnalysis,
          metadata: {
            pipelineVersion: result.pipelineVersion,
            provider: result.provider,
            model: result.aiModel,
            tokensUsed: result.tokensUsed,
            inputTokens: result.inputTokens,
            outputTokens: result.outputTokens,
            processingTimeMs: result.processingTimeMs,
            latencyMs: result.latencyMs,
            overallConfidence: result.overallConfidence,
            fieldConfidences: result.fieldConfidences,
            finishReason: result.finishReason,
            apiKeyMasked: result.apiKeyMasked,
          },
        });

        await aiContextService.updateStatus(context.id, 'approved');

        setJobMetadata(job.jobId, {
          provider: result.provider,
          model: result.aiModel,
          inputTokens: result.inputTokens,
          outputTokens: result.outputTokens,
          totalTokens: result.tokensUsed,
          latencyMs: result.latencyMs,
          durationMs: result.processingTimeMs,
          finishReason: result.finishReason,
          apiKeyMasked: result.apiKeyMasked,
        });

        completeJob(job.jobId, { caseStudies: autoFillDataArray },'generated');

        console.log(`[CaseStudy-AutoFill] Job ${job.jobId} completed. Generated ${autoFillDataArray.length} case studies`);
      } catch (err: any) {
        console.error(`[CaseStudy-AutoFill] Job ${job.jobId} failed:`, err.message);
        failJob(job.jobId, err.message || 'AI generation failed');
      }
    });
  }
);

// ============================================
// POST /regenerate
// ============================================

router.post(
  '/regenerate',
  requirePermission('case-studies', 'ai-generate'),
  [
    body('companyId').notEmpty().withMessage('Company ID is required'),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({ error: 'Validation failed', details: errors.array() });
      return;
    }

    const { companyId, existingCaseStudyData } = req.body;
    const language = req.body.language || 'English';

    // Create job and return immediately
    const job = createJob('case-studies', companyId, req.body._moduleId);
    res.status(202).json({ jobId: job.jobId, status: 'processing' });

    // Run pipeline in background
    setImmediate(async () => {
      try {
        const { Company, BusinessProfile, ICP } = getModels();
        const company = await Company.findById(companyId);
        if (!company) {
          failJob(job.jobId, 'Company not found');
          return;
        }

        let businessProfile: any = null;
        try { businessProfile = await BusinessProfile.findOne({ companyId }); } catch {}

        const companyContexts = await aiContextService.getByCompany(companyId, 'company-creation');
        const latestCompanyContext = companyContexts.find((c: any) => {
          const a = c.analysis?.toObject?.() || c.analysis || {};
          return c.status === 'approved' || a.industryType || a.businessModel || a.businessSummary;
        });

        let icpData: any = null;
        try { icpData = await ICP.findOne({ companyId, isActive: true }).sort({ createdAt: -1 }); } catch {}

        // Load brand strategy context for enrichment
        let brandStrategyData: any = null;
        try {
          const { ModuleData } = getModels();
          const brandStrategyDoc = await ModuleData.findOne({ moduleId: 'brand-strategy', companyId });
          if (brandStrategyDoc?.data) {
            brandStrategyData = brandStrategyDoc.data;
          }
        } catch {}

        // Build pipeline inputs with existing case study data for regeneration
        const pipelineInputs: CaseStudyPipelineInputs = {
          companyName: company.name,
          companyDescription: company.description || businessProfile?.description || undefined,
          companyIndustry: businessProfile?.primaryIndustry || undefined,
          companyBusinessModel: businessProfile?.businessModel || undefined,
          companyTargetAudience: undefined,
          companyPrimaryOffering: undefined,
          companyUsps: undefined,
          targetCount: 1, // Regenerate single case study
          language,
          // Existing case study identity for regeneration
          existingTitle: existingCaseStudyData?.title || undefined,
          existingIndustry: existingCaseStudyData?.industry || undefined,
          existingDepartment: existingCaseStudyData?.department || undefined,
        };

        if (latestCompanyContext) {
          const analysis = (latestCompanyContext as any).analysis?.toObject?.() || (latestCompanyContext as any).analysis || {};
          if (analysis.industryType && !pipelineInputs.companyIndustry) pipelineInputs.companyIndustry = analysis.industryType;
          if (analysis.businessModel && !pipelineInputs.companyBusinessModel) pipelineInputs.companyBusinessModel = analysis.businessModel;
          if (analysis.targetAudience?.primary) pipelineInputs.companyTargetAudience = analysis.targetAudience.primary;
          if (analysis.primaryOffering) pipelineInputs.companyPrimaryOffering = analysis.primaryOffering;
          if (analysis.uspSuggestions?.length) pipelineInputs.companyUsps = analysis.uspSuggestions;
        }

        if (icpData) {
          pipelineInputs.icpName = icpData.name || undefined;
          pipelineInputs.icpIndustry = icpData.industry || undefined;
          pipelineInputs.icpPainPoints = icpData.painPoints || undefined;
          pipelineInputs.icpBusinessGoals = icpData.businessGoals || undefined;
        }

        if (brandStrategyData) {
          pipelineInputs.brandArchetype = brandStrategyData.brandArchetype || undefined;
          pipelineInputs.brandPersonality = brandStrategyData.brandPersonality || undefined;
          pipelineInputs.brandValues = brandStrategyData.brandValues || undefined;
          pipelineInputs.brandPositioning = brandStrategyData.brandPositioning || undefined;
          pipelineInputs.brandVoice = brandStrategyData.brandVoice || undefined;
        }

        updateJobProgress(job.jobId, 10, 'Preparing context...');
        const pipeline = new CaseStudyPipeline(pipelineInputs, (progress, step) => {
          updateJobProgress(job.jobId, progress, step);
          setJobMetadata(job.jobId, pipeline.getLiveMetadata());
        });
        const result = await pipeline.run();

        // Map each case study through the auto-fill mapping function
        const autoFillDataArray = result.caseStudies.map((csAnalysis: Record<string, any>) =>
          computeCaseStudyAutoFillMapping(csAnalysis)
        ).filter((data: Record<string, any>) => data.title);

        const combinedAnalysis: Record<string, any> = {
          caseStudies: result.caseStudies,
          pipelineVersion: result.pipelineVersion,
          provider: result.provider,
          aiModel: result.aiModel,
          tokensUsed: result.tokensUsed,
          inputTokens: result.inputTokens,
          outputTokens: result.outputTokens,
          processingTimeMs: result.processingTimeMs,
          overallConfidence: result.overallConfidence,
          latencyMs: result.latencyMs,
        };

        const context = await aiContextService.create({
          companyId,
          moduleSource: 'case-studies',
          analysisType: 'full-analysis',
          inputs: { companyName: company.name, description: pipelineInputs.companyDescription },
          analysis: combinedAnalysis,
          metadata: {
            pipelineVersion: result.pipelineVersion,
            provider: result.provider,
            model: result.aiModel,
            tokensUsed: result.tokensUsed,
            inputTokens: result.inputTokens,
            outputTokens: result.outputTokens,
            processingTimeMs: result.processingTimeMs,
            latencyMs: result.latencyMs,
            overallConfidence: result.overallConfidence,
            fieldConfidences: result.fieldConfidences,
            finishReason: result.finishReason,
            apiKeyMasked: result.apiKeyMasked,
          },
        });

        await aiContextService.updateStatus(context.id, 'approved');

        setJobMetadata(job.jobId, {
          provider: result.provider,
          model: result.aiModel,
          inputTokens: result.inputTokens,
          outputTokens: result.outputTokens,
          totalTokens: result.tokensUsed,
          latencyMs: result.latencyMs,
          durationMs: result.processingTimeMs,
          finishReason: result.finishReason,
          apiKeyMasked: result.apiKeyMasked,
        });

        completeJob(job.jobId, { caseStudies: autoFillDataArray },'regenerated');

        console.log(`[CaseStudy-Regenerate] Job ${job.jobId} completed. Regenerated ${autoFillDataArray.length} case studies`);
      } catch (err: any) {
        console.error(`[CaseStudy-Regenerate] Job ${job.jobId} failed:`, err.message);
        failJob(job.jobId, err.message || 'AI regeneration failed');
      }
    });
  }
);

// ============================================
// POST /generate
// ============================================

router.post(
  '/generate',
  requirePermission('case-studies', 'ai-generate'),
  [
    body('companyId').notEmpty().withMessage('Company ID is required'),
    body('title').notEmpty().withMessage('Title is required'),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({ error: 'Validation failed', details: errors.array() });
      return;
    }

    const { companyId, title, department, industry, clientName, challengeContext } = req.body;
    const language = req.body.language || 'English';

    // Create job and return immediately
    const job = createJob('case-studies', companyId, req.body._moduleId);
    res.status(202).json({ jobId: job.jobId, status: 'processing' });

    // Run generation in background
    setImmediate(async () => {
      try {
        const { Company, BusinessProfile, ICP } = getModels();
        const company = await Company.findById(companyId);
        if (!company) {
          failJob(job.jobId, 'Company not found');
          return;
        }

        let businessProfile: any = null;
        try { businessProfile = await BusinessProfile.findOne({ companyId }); } catch {}

        const companyContexts = await aiContextService.getByCompany(companyId, 'company-creation');
        const latestCompanyContext = companyContexts.find((c: any) => {
          const a = c.analysis?.toObject?.() || c.analysis || {};
          return c.status === 'approved' || a.industryType || a.businessModel || a.businessSummary;
        });

        let icpData: any = null;
        try { icpData = await ICP.findOne({ companyId, isActive: true }).sort({ createdAt: -1 }); } catch {}

        // Load brand strategy context for enrichment
        let brandStrategyData: any = null;
        try {
          const { ModuleData } = getModels();
          const brandStrategyDoc = await ModuleData.findOne({ moduleId: 'brand-strategy', companyId });
          if (brandStrategyDoc?.data) {
            brandStrategyData = brandStrategyDoc.data;
          }
        } catch {}

        // Build pipeline inputs with comprehensive context
        const contextParts: string[] = [];
        contextParts.push(`Generate a case study titled: "${title}"`);
        if (clientName) contextParts.push(`Client name: ${clientName}`);
        if (department) contextParts.push(`Department: ${department}`);
        if (industry) contextParts.push(`Industry: ${industry}`);
        if (challengeContext) contextParts.push(`Context: ${challengeContext}`);

        // Always include company name in context
        contextParts.push(`Company: ${company.name || 'A technology company'}`);

        const generationContext = contextParts.join('. ');

        console.log(`[CaseStudy-Generate] Job ${job.jobId} - Generation context:`, generationContext);

        // Build comprehensive description for AI - ensure there's always enough context
        let companyDescription = generationContext;

        // Add business profile context if available
        if (businessProfile?.description) {
          companyDescription = `${generationContext}. Company Description: ${businessProfile.description}`;
        }

        // Add ICP context if available
        if (icpData?.painPoints && icpData.painPoints.length > 0) {
          companyDescription += `. Target customer pain points: ${icpData.painPoints.join(', ')}`;
        }

        // Add brand context if available
        if (brandStrategyData?.brandPositioning) {
          companyDescription += `. Brand positioning: ${brandStrategyData.brandPositioning}`;
        }

        // Build pipeline inputs with comprehensive defaults
        const pipelineInputs: CaseStudyPipelineInputs = {
          companyName: company.name || 'Company',
          companyIndustry: industry || businessProfile?.industry || 'technology',
          companyDescription: companyDescription,
          customDescription: challengeContext || `Create a professional case study about: ${title}. Focus on ${department || 'marketing'} outcomes in the ${industry || 'technology'} industry.`,
          targetCount: 1,
          departmentFocus: department || 'marketing',
          industryFocus: industry || 'technology',
          companyBusinessModel: undefined,
          companyTargetAudience: undefined,
          companyPrimaryOffering: undefined,
          companyUsps: undefined,
          icpName: undefined,
          icpIndustry: undefined,
          icpPainPoints: undefined,
          icpBusinessGoals: undefined,
          brandArchetype: undefined,
          brandPersonality: undefined,
          brandValues: undefined,
          brandPositioning: undefined,
          brandVoice: undefined,
          language,
        };

        // Enrich with business profile data if available
        if (businessProfile) {
          if (businessProfile.industry) {
            pipelineInputs.companyIndustry = businessProfile.industry;
          }
          if (businessProfile.targetAudience) {
            pipelineInputs.companyTargetAudience = businessProfile.targetAudience;
          }
          if (businessProfile.primaryOffering) {
            pipelineInputs.companyPrimaryOffering = businessProfile.primaryOffering;
          }
        }

        if (latestCompanyContext) {
          const analysis = (latestCompanyContext as any).analysis?.toObject?.() || (latestCompanyContext as any).analysis || {};
          if (analysis.industryType && !pipelineInputs.companyIndustry) pipelineInputs.companyIndustry = analysis.industryType;
          if (analysis.businessModel && !pipelineInputs.companyBusinessModel) pipelineInputs.companyBusinessModel = analysis.businessModel;
          if (analysis.targetAudience?.primary) pipelineInputs.companyTargetAudience = analysis.targetAudience.primary;
          if (analysis.primaryOffering) pipelineInputs.companyPrimaryOffering = analysis.primaryOffering;
          if (analysis.uspSuggestions?.length) pipelineInputs.companyUsps = analysis.uspSuggestions;
        }

        if (icpData) {
          pipelineInputs.icpName = icpData.name || undefined;
          pipelineInputs.icpIndustry = icpData.industry || undefined;
          pipelineInputs.icpPainPoints = icpData.painPoints || undefined;
          pipelineInputs.icpBusinessGoals = icpData.businessGoals || undefined;
        }

        if (brandStrategyData) {
          pipelineInputs.brandArchetype = brandStrategyData.brandArchetype || undefined;
          pipelineInputs.brandPersonality = brandStrategyData.brandPersonality || undefined;
          pipelineInputs.brandValues = brandStrategyData.brandValues || undefined;
          pipelineInputs.brandPositioning = brandStrategyData.brandPositioning || undefined;
          pipelineInputs.brandVoice = brandStrategyData.brandVoice || undefined;
        }

        updateJobProgress(job.jobId, 10, 'Generating case study...');

        try {
          const pipeline = new CaseStudyPipeline(pipelineInputs, (progress, step) => {
            updateJobProgress(job.jobId, progress, step);
            // Push what the pipeline knows so far (provider, model, running token
            // counts) on every progress tick — the poller picks it up on its next
            // pass, so the screen fills in as generation proceeds.
            setJobMetadata(job.jobId, pipeline.getLiveMetadata());
          });
          const result = await pipeline.run();

          // Check if pipeline returned any errors
          if (result.errors && result.errors.length > 0) {
            console.error(`[CaseStudy-Generate] Job ${job.jobId} - Pipeline errors:`, result.errors);
            throw new Error(`AI generation failed: ${result.errors.join(', ')}`);
          }

          // Check if we got valid results
          if (!result.caseStudies || result.caseStudies.length === 0) {
            throw new Error('AI did not generate any case studies. Please try again with more context.');
          }

          // Override the title with user-provided title
          if (result.caseStudies && result.caseStudies.length > 0) {
            result.caseStudies[0].title = title;
            if (clientName) result.caseStudies[0].clientName = clientName;
            if (department) result.caseStudies[0].department = department;
            if (industry) result.caseStudies[0].industry = industry;
          }

          // Map case study through the auto-fill mapping function
          const autoFillDataArray = result.caseStudies.map((csAnalysis: Record<string, any>) =>
            computeCaseStudyAutoFillMapping(csAnalysis)
          ).filter((data: Record<string, any>) => data.title);

          if (autoFillDataArray.length === 0) {
            throw new Error('Failed to process generated case study. Please try again.');
          }

          const combinedAnalysis: Record<string, any> = {
            caseStudies: result.caseStudies,
            pipelineVersion: result.pipelineVersion,
            provider: result.provider,
            aiModel: result.aiModel,
            tokensUsed: result.tokensUsed,
            inputTokens: result.inputTokens,
            outputTokens: result.outputTokens,
            processingTimeMs: result.processingTimeMs,
            overallConfidence: result.overallConfidence,
            latencyMs: result.latencyMs,
          };

          const context = await aiContextService.create({
            companyId,
            moduleSource: 'case-studies',
            analysisType: 'full-analysis',
            inputs: {
              companyName: company.name,
              title,
              department,
              industry,
              clientName,
              challengeContext
            },
            analysis: combinedAnalysis,
            metadata: {
              pipelineVersion: result.pipelineVersion,
              provider: result.provider,
              model: result.aiModel,
              tokensUsed: result.tokensUsed,
              inputTokens: result.inputTokens,
              outputTokens: result.outputTokens,
              processingTimeMs: result.processingTimeMs,
              latencyMs: result.latencyMs,
              overallConfidence: result.overallConfidence,
              fieldConfidences: result.fieldConfidences,
              finishReason: result.finishReason,
              apiKeyMasked: result.apiKeyMasked,
            },
          });

          await aiContextService.updateStatus(context.id, 'approved');

          // Final, authoritative execution details for the completed row.
          setJobMetadata(job.jobId, {
            provider: result.provider,
            model: result.aiModel,
            inputTokens: result.inputTokens,
            outputTokens: result.outputTokens,
            totalTokens: result.tokensUsed,
            latencyMs: result.latencyMs,
            durationMs: result.processingTimeMs,
            finishReason: result.finishReason,
            apiKeyMasked: result.apiKeyMasked,
          });

          completeJob(job.jobId, { caseStudies: autoFillDataArray }, 'generated');

          console.log(`[CaseStudy-Generate] Job ${job.jobId} completed. Generated ${autoFillDataArray.length} case study`);
        } catch (err: any) {
          console.error(`[CaseStudy-Generate] Job ${job.jobId} failed:`, err.message);
          failJob(job.jobId, err.message || 'AI generation failed');
        }
      } catch (err: any) {
        console.error(`[CaseStudy-Generate] Job ${job.jobId} failed:`, err.message);
        failJob(job.jobId, err.message || 'AI generation failed');
      }
    });
  }
);

export default router;