All files / services/workflow-service-api/src index.js

54.7% Statements 547/1000
49.52% Branches 52/105
87.5% Functions 7/8
54.7% Lines 547/1000

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 10011x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 12x 12x 1x 12x 12x 12x 12x 12x 12x 1x 12x 12x 12x 12x 12x 12x 6x       6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x                             6x 6x 6x 6x                             6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 6x       6x 6x 6x 6x 6x     6x 3x 3x 3x 3x     3x 6x               6x 6x     12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x       13x 13x 13x 13x 13x     13x 1x 1x 1x 15x 15x 15x 15x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x     9x 9x 6x 6x 6x 15x       15x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x                                                           1x 1x 1x 1x 1x 1x 1x                                                                                                                   1x 1x 1x 1x 1x 1x 1x                                                                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                   1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x             3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 13x 13x 13x 13x 13x 9x 9x 9x 9x 9x 13x 3x 3x 3x 3x             3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x               3x 12x 12x 13x 13x 13x 13x 13x 13x 13x 13x 13x 9x 9x 9x             9x 12x 12x 12x 12x 12x 12x 12x 12x 13x 13x 13x 13x 13x 13x 9x 9x 9x 9x 13x 3x 3x                         12x 12x 12x 12x 13x 13x 12x 12x 12x 12x 13x 3x 3x 13x     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 13x 9x 9x 13x 3x 3x     12x 12x 12x 12x 12x 12x 13x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * API HTTP pour le service Workflow
 * Gère les configs métier (workflows) et le lancement de synthèses
 */
 
const express = require('express');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const mongoose = require('mongoose');
const axios = require('axios');
const config = require('./shared/config');
const { Workflow } = require('./shared/models');
// LEGACY: SynthesisJob était importé ici mais est désormais géré par job-manager-service via Redis/SSE
const schemas = require('./shared/schemas');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const CONFIG_SERVICE_URL = process.env.CONFIG_SERVICE_URL || 'http://config-service:8000';
const { addInternalKey, verifyInternalToken } = require('../shared/internalAuth');
const { signedAxios } = require('../shared/signedAxios');
const SERVICE_NAME = process.env.SERVICE_NAME || 'workflow-service-api';
// Module partagé (source unique) : org-auth expose getUserOrganizations + checkOrgAccess.
const { getUserOrganizations, checkOrgAccess } = require('../shared/validation/src/org-auth');
 
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const Redis = require('ioredis');
 
const JOB_MANAGER_SERVICE_URL = process.env.JOB_MANAGER_SERVICE_URL || 'http://job-manager-service:8000';
const KNOWLEDGE_BASE_URL = process.env.KNOWLEDGE_BASE_URL || 'http://knowledge-base-service:8000';
const { buildRefinementPlans } = require('./refinementPlans');
 
const app = express();
const PORT = config.port;
 
mongoose.connect(config.mongodbUri)
  .then(() => console.log('✅ WorkflowAPI connected to MongoDB'))
  .catch(err => console.error('❌ WorkflowAPI MongoDB connection error:', err));
 
// ============================================================================
// Redis client for config config lookup
// ============================================================================
const JOB_POOL_PREFIX = 'pool:job:';
const JOB_POOL_SUFFIX = ':params';
const JOB_TTL = 86400;
 
let redisClient = null;
function getRedisClient() {
  if (!redisClient) {
    const redisHost = process.env.REDIS_HOST || 'redis';
    const redisPort = parseInt(process.env.REDIS_PORT || '6379');
    const redisPassword = process.env.REDIS_PASSWORD || undefined;
    
    redisClient = new Redis({
      host: redisHost,
      port: redisPort,
      password: redisPassword,
      retryStrategy: (times) => Math.min(times * 50, 2000),
    });
    
    redisClient.on('error', (err) => {
      console.error('[WorkflowAPI/Redis] Error:', err.message);
    });
    
    redisClient.on('connect', () => {
      console.log('[WorkflowAPI/Redis] Connected');
    });
  }
  return redisClient;
}
 
async function storeJobById(jobId, jobData) {
  const redis = getRedisClient();
  const key = `${JOB_POOL_PREFIX}${jobId}${JOB_POOL_SUFFIX}`;
  await redis.setex(key, JOB_TTL, JSON.stringify(jobData));
  return jobId;
}
 
async function getWorkflowArgsConfig(req, sourceType, detection, isFileType, browserProvider) {
  const token = req.headers['authorization']?.split(' ')[1];
  const organizationId = req.params.organizationId || req.headers['x-organization-id'] || null;
  
  // Priority 1: Authorization header → fetch from config-service (requires organizationId)
  if (token && config.configServiceUrl) {
    if (!organizationId) {
      console.warn('[getWorkflowArgsConfig] Cannot resolve API key: no organizationId in request');
      return { llmApiKey: null, authToken: token, userId: null, source: 'no_org_id' };
    }
    
    console.log(`[getWorkflowArgsConfig] Using Authorization header, fetching from config-service for org ${organizationId}`);
    let userId = null;
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      userId = decoded?.userId || null;
    } catch (e) {
      console.warn('[getWorkflowArgsConfig] Invalid JWT signature:', e.message);
    }
    const result = { llmApiKey: null, authToken: token, userId, source: 'config-service' };
    
    try {
      const configUrl = `${config.configServiceUrl}/${organizationId}/config/openrouter`;
      const configResponse = await axios.get(
        configUrl,
        { headers: { 'Authorization': `Bearer ${token}` }, timeout: 5000 }
      );
      if (configResponse.data?.success) {
        result.llmApiKey = configResponse.data.data.value;
        console.log(`[getWorkflowArgsConfig] OpenRouter key resolved: ${result.llmApiKey?.substring(0, 10)}...`);
      }
    } catch (e) {
      console.warn('[getWorkflowArgsConfig] Could not fetch OpenRouter API key:', e.message);
    }
    
    if (isFileType) {
      try {
        const configUrl = `${config.configServiceUrl}/${organizationId}/config/marker`;
        const configResponse = await axios.get(
          configUrl,
          { headers: { 'Authorization': `Bearer ${token}` }, timeout: 5000 }
        );
        if (configResponse.data?.success) {
          result.markerApiKey = configResponse.data.data.value;
          console.log(`[getWorkflowArgsConfig] Marker key resolved: ${result.markerApiKey ? 'YES' : 'NO'}`);
        }
      } catch (e) {
        console.warn('[getWorkflowArgsConfig] Could not fetch Marker API key:', e.message);
      }
    }
 
    // Endpoint navigateur (BrightData) résolu ici, comme les clés LLM/Marker,
    // pour que l'activité scrapeWebPage le reçoive en paramètre (pas d'appel config-service côté worker).
    if (browserProvider === 'brightdata') {
      try {
        const configUrl = `${config.configServiceUrl}/${organizationId}/config/browser.brightdata.wsEndpoint`;
        const configResponse = await axios.get(
          configUrl,
          { headers: { 'Authorization': `Bearer ${token}` }, timeout: 5000 }
        );
        if (configResponse.data?.success) {
          result.brightdataWs = configResponse.data.data.value;
          console.log(`[getWorkflowArgsConfig] BrightData endpoint resolved: ${result.brightdataWs ? 'YES' : 'NO'}`);
        }
      } catch (e) {
        console.warn('[getWorkflowArgsConfig] Could not fetch BrightData endpoint:', e.message);
      }
    }
 
    return result;
  }
  
  // Priority 2: appel sans JWT :
  //   - machine (activité/crawler) → HMAC `x-internal-token` ;
  //   - API-key via la gateway → contexte `x-organization-id`.
  // Dans les deux cas, les clés sont résolues à la demande via les routes internes
  // du config-service ; aucun credential utilisateur n'est transmis (D2/D8).
  const internalToken = req.headers['x-internal-token'];
  const hasInternalHmac = !!(internalToken && verifyInternalToken(internalToken));
  const hasGatewayContext = !!req.headers['x-organization-id'];
  if (hasInternalHmac || hasGatewayContext) {
    if (!organizationId) {
      console.warn('[getWorkflowArgsConfig] Internal/API-key call without organizationId');
      return { llmApiKey: null, authToken: null, userId: null, source: 'no_org_id' };
    }
    const result = { llmApiKey: null, authToken: null, userId: null, source: hasInternalHmac ? 'internal-hmac' : 'gateway-context' };
    try {
      const r = await signedAxios.get(`/internal/${organizationId}/config/openrouter`, { timeout: 5000 });
      if (r.data?.success) result.llmApiKey = r.data.data.value;
    } catch (e) {
      console.warn('[getWorkflowArgsConfig] Could not fetch OpenRouter API key (internal):', e.message);
    }
    if (isFileType) {
      try {
        const r = await signedAxios.get(`/internal/${organizationId}/config/marker`, { timeout: 5000 });
        if (r.data?.success) result.markerApiKey = r.data.data.value;
      } catch (e) {
        console.warn('[getWorkflowArgsConfig] Could not fetch Marker API key (internal):', e.message);
      }
    }
    if (browserProvider === 'brightdata') {
      try {
        const r = await signedAxios.get(`/internal/${organizationId}/config/browser.brightdata.wsEndpoint`, { timeout: 5000 });
        if (r.data?.success) result.brightdataWs = r.data.data.value;
      } catch (e) {
        console.warn('[getWorkflowArgsConfig] Could not fetch BrightData endpoint (internal):', e.message);
      }
    }
    return result;
  }

  return { llmApiKey: null, authToken: null, userId: null, source: 'no_auth' };
}
 
// Middleware
app.use(cors());
app.use(express.json({ limit: '100mb' }));
 
// ============================================================================
// MinIO / S3 Configuration
// ============================================================================
 
const s3Client = new S3Client({
  endpoint: config.minioEndpoint,
  forcePathStyle: true,
  region: 'us-east-1',
  credentials: {
    accessKeyId: config.minioAccessKey,
    secretAccessKey: config.minioSecretKey
  }
});
 
// Multer configuration for file upload (memory storage)
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 100 * 1024 * 1024 // 100MB limit
  }
});
 
// ============================================================================
// Health Check
// ============================================================================
 
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    service: 'workflow-service-api',
    version: '1.0.0',
    temporal: config.temporalAddress,
    queue: config.temporalTaskQueue
  });
});
 
// ============================================================================
// CRUD Routes for Workflows (configs métier)
// ============================================================================
 
// Helper to extract organizationId from request
// Priority: x-organization-id header (from gateway) > URL params
function getOrganizationIdFromRequest(req) {
  const orgIdFromHeader = req.headers['x-organization-id'];
  if (orgIdFromHeader) {
    console.log(`[getOrganizationIdFromRequest] Got orgId from header: ${orgIdFromHeader}`);
    return orgIdFromHeader;
  }
  const orgIdFromParams = req.params.organizationId;
  if (orgIdFromParams) {
    console.log(`[getOrganizationIdFromRequest] Got orgId from params: ${orgIdFromParams}`);
    return orgIdFromParams;
  }
  console.log('[getOrganizationIdFromRequest] No orgId found');
  return null;
}
 
// Helper to extract userId from a verified JWT token (frontend/user calls only).
// Les appels internes machine utilisent le HMAC et ne portent pas d'identité utilisateur.
async function getUserIdFromRequest(req) {
  try {
    const authHeader = req.headers['authorization'];
    if (authHeader) {
      const token = authHeader.split(' ')[1];
      if (token) {
        try {
          const decoded = jwt.verify(token, process.env.JWT_SECRET);
          const userId = decoded?.userId || null;
          if (userId) {
            console.log(`[getUserIdFromRequest] Got userId from JWT: ${userId}`);
            return userId;
          }
        } catch (e) {
          console.warn('[getUserIdFromRequest] Invalid JWT signature:', e.message);
        }
      }
    }
 
    console.log('[getUserIdFromRequest] No valid userId found');
    return null;
  } catch (e) {
    console.error('[getUserIdFromRequest] Error:', e.message);
    return null;
  }
}
 
/**
 * GET /:organizationId/workflows
 * List all workflows for the organization
 */
app.get('/:organizationId/workflows', async (req, res) => {
  try {
    const userId = await getUserIdFromRequest(req);
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: 'Authentication required'
      });
    }
 
    const { organizationId } = req.params;
 
    const workflows = await Workflow.find({
      organizationId,
      isActive: true
    }).sort({ createdAt: -1 });
 
    res.json({
      success: true,
      data: workflows
    });
  } catch (error) {
    console.error('[WorkflowAPI] Error listing workflows:', error);
    res.status(500).json({
      success: false,
      message: 'Error retrieving workflows',
      error: error.message
    });
  }
});
 
/**
 * POST /workflows
 * Create a new workflow
 */
app.post('/workflows', async (req, res) => {
  try {
    const userId = await getUserIdFromRequest(req);
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: 'Authentication required'
      });
    }
 
    const {
      name,
      description,
      destinations,
      organizationId
    } = req.body;
 
    if (!name) {
      return res.status(400).json({
        success: false,
        message: 'Name is required'
      });
    }
 
    if (!organizationId) {
      return res.status(400).json({
        success: false,
        message: 'organizationId is required'
      });
    }
 
    // Le raffinage (mode/spec/modèle) vit exclusivement dans chaque destination
    // (destination.refinement) : plus aucun champ de raffinage au niveau du workflow.
    const workflow = new Workflow({
      userId,
      organizationId,
      name,
      description: description || '',
      destinations: destinations || []
    });
 
    await workflow.save();
 
    res.status(201).json({
      success: true,
      message: 'Workflow created successfully',
      data: workflow
    });
  } catch (error) {
    console.error('[WorkflowAPI] Error creating workflow:', error);
    res.status(500).json({
      success: false,
      message: 'Error creating workflow',
      error: error.message
    });
  }
});
 
/**
 * GET /workflows/:id
 * Get a specific workflow
 */
app.get('/workflows/:id', async (req, res) => {
  try {
    const workflow = await Workflow.findOne({
      _id: req.params.id,
      isActive: true
    });

    if (!workflow) {
      return res.status(404).json({
        success: false,
        message: 'Workflow not found'
      });
    }

    if (!await checkOrgAccess(workflow.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    res.json({
      success: true,
      data: workflow
    });
  } catch (error) {
    console.error('[WorkflowAPI] Error getting workflow:', error);
    res.status(500).json({
      success: false,
      message: 'Error retrieving workflow',
      error: error.message
    });
  }
});
 
/**
 * PUT /workflows/:id
 * Update a workflow
 */
app.put('/workflows/:id', async (req, res) => {
  try {
    const userId = await getUserIdFromRequest(req);
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: 'Authentication required'
      });
    }

    const currentWorkflow = await Workflow.findOne({
      _id: req.params.id, isActive: true
    });
    if (!currentWorkflow) {
      return res.status(404).json({ success: false, message: 'Workflow not found' });
    }
    if (!await checkOrgAccess(currentWorkflow.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    const {
      name,
      description,
      destinations
    } = req.body;

    const updates = {};

    if (name !== undefined) updates.name = name;
    if (description !== undefined) updates.description = description;
    if (destinations !== undefined) updates.destinations = destinations;

    const workflow = await Workflow.findOneAndUpdate(
      { _id: req.params.id, isActive: true },
      { $set: updates },
      { new: true }
    );

    if (!workflow) {
      return res.status(404).json({
        success: false,
        message: 'Workflow not found'
      });
    }

    res.json({
      success: true,
      message: 'Workflow updated successfully',
      data: workflow
    });
  } catch (error) {
    console.error('[WorkflowAPI] Error updating workflow:', error);
    res.status(500).json({
      success: false,
      message: 'Error updating workflow',
      error: error.message
    });
  }
});
 
/**
 * DELETE /workflows/:id
 * Delete a workflow (soft delete)
 */
app.delete('/workflows/:id', async (req, res) => {
  try {
    const userId = await getUserIdFromRequest(req);
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: 'Authentication required'
      });
    }

    const workflow = await Workflow.findOneAndUpdate(
      { _id: req.params.id, isActive: true },
      { $set: { isActive: false } },
      { new: true }
    );

    if (!workflow) {
      return res.status(404).json({
        success: false,
        message: 'Workflow not found'
      });
    }
    if (!await checkOrgAccess(workflow.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    res.json({
      success: true,
      message: 'Workflow deleted successfully'
    });
  } catch (error) {
    console.error('[WorkflowAPI] Error deleting workflow:', error);
    res.status(500).json({
      success: false,
      message: 'Error deleting workflow',
      error: error.message
    });
  }
});
 
// ============================================================================
// File Upload Route
// ============================================================================
 
/**
 * POST /upload and /:organizationId/upload
 * Upload a file to MinIO and return a fileId for workflow processing
 */
app.post('/upload', upload.single('file'), async (req, res) => {
  return handleUpload(req, res);
});
 
app.post('/:organizationId/upload', upload.single('file'), async (req, res) => {
  return handleUpload(req, res);
});
 
/**
 * POST /:organizationId/semantic-assets
 * Upload d'un fichier OWL/SHACL pour un raffinage sémantique vers Affichage/API.
 * Stocké dans MinIO (D11) ; renvoie la clé MinIO à placer dans la destination.
 */
app.post('/:organizationId/semantic-assets', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ success: false, message: 'No file provided' });
    }
    const key = `semantic-assets/${uuidv4()}/${req.file.originalname}`;
    await s3Client.send(new PutObjectCommand({
      Bucket: config.minioBucket,
      Key: key,
      Body: req.file.buffer,
      ContentType: req.file.mimetype,
    }));
    console.log(`[Upload] Semantic asset: ${req.file.originalname} -> ${key} (${req.file.size} bytes)`);
    res.json({
      success: true,
      data: {
        key,
        filename: req.file.originalname,
        size: req.file.size,
        contentType: req.file.mimetype,
      },
    });
  } catch (error) {
    console.error('[Upload] Semantic asset error:', error);
    res.status(500).json({ success: false, message: 'Error uploading semantic asset', error: error.message });
  }
});
 
async function handleUpload(req, res) {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: 'No file provided'
      });
    }
 
    const fileId = uuidv4();
    const filename = req.file.originalname;
    
    // Store file in the format expected by the workflow: {fileId}/input/{filename}
    const key = `${fileId}/input/${filename}`;
 
    // Upload to MinIO
    await s3Client.send(new PutObjectCommand({
      Bucket: config.minioBucket,
      Key: key,
      Body: req.file.buffer,
      ContentType: req.file.mimetype
    }));
 
    console.log(`[Upload] File uploaded: ${filename} -> ${key} (${req.file.size} bytes)`);
 
    res.json({
      success: true,
      data: {
        fileId: fileId,
        filename: filename,
        size: req.file.size,
        mimeType: req.file.mimetype
      }
    });
  } catch (error) {
    console.error('[Upload] Error:', error);
    res.status(500).json({
      success: false,
      message: 'Error uploading file',
      error: error.message
    });
  }
}
 
// ============================================================================
// Extraction Routes
// ============================================================================
 
/**
 * Détecte le type d'extraction basé sur les paramètres de la requête
 * Retourne: { type: 'url'|'input', mode: 'url'|'fileUrl'|'fileUploaded', input: value }
 * 
 * Pour les URLs (web ou fichier), retourne toujours type='url' — la résolution réelle
 * (redirect, content-type) est déléguée à une activité Temporal dans le workflow-service-worker
 */
function detectType(body) {
  // Mode 1: fileUploaded - Fichier déjà uploadé (fileId)
  if (body.fileId) {
    return {
      type: 'file',
      mode: 'fileUploaded',
      input: body.fileId
    };
  }
  
  // Mode 2: URL vers un fichier ou une page web
  // On ne fait plus la distinction ici — c'est le workflow-service-worker qui résout via HEAD
  if (body.url || body.fileUrl) {
    const inputUrl = body.url || body.fileUrl;
    return {
      type: 'url',
      mode: body.fileUrl ? 'fileUrl' : 'web',
      input: inputUrl
    };
  }
  
  throw new Error('Fournissez une URL (url ou fileUrl), ou un fileId (fileId)');
}
 
/**
 * POST /:organizationId/workflow/:workflowId/extract
 * Endpoint unifié pour extraction (web, fileUrl, fileUploaded)
 */
app.post('/:organizationId/workflow/:workflowId/extract', async (req, res) => {
  try {
    const { workflowId, organizationId } = req.params;
    const userId = await getUserIdFromRequest(req);

    
    // Valider le body avec le schéma unifié
    const { error, value } = schemas.extract.validate(req.body);
    if (error) {
      return res.status(400).json({
        success: false,
        message: 'Validation error',
        error: error.details[0].message
      });
    }

    const { maxItems, destinations: bodyDestinations } = value;
    const detection = detectType(value);
    const jobId = value.idempotencyKey || uuidv4();

    console.log(`[Extract] ${detection.type} (${detection.mode}): ${jobId}, workflowId: ${workflowId}`);

    // Récupérer la configuration depuis MongoDB
    let workflowData;
    try {
      const workflowDoc = await Workflow.findOne({
        _id: workflowId,
        userId,
        isActive: true
      }).lean();
      workflowData = workflowDoc;
    } catch (e) {
      console.error('[WorkflowAPI] Failed to fetch workflow from DB:', e.message);
    }

    if (!workflowData) {
      return res.status(404).json({
        success: false,
        message: 'Workflow not found'
      });
    }

    // Plafond d'items optionnel de la requête (le workflow ne porte plus de spec).
    const finalMaxItems = maxItems;

    // HARMONISATION: Transformer la config DB en format générique
    // Les destinations viennent du body (surcharge) ou de la config workflow
    const destinations = bodyDestinations && bodyDestinations.length > 0
      ? bodyDestinations
      : (workflowData.destinations || []);

    // Résoudre le plan de raffinage à partir des destinations (aucun repli de workflow).
    let refinementPlans = [];
    if (destinations.length > 0) {
      try {
        const authHeaderToken = req.headers['authorization']?.split(' ')[1] || null;
        refinementPlans = await buildRefinementPlans(destinations, {
          maxItems: finalMaxItems
        }, workflowData.organizationId, undefined);
      } catch (planError) {
        return res.status(400).json({
          success: false,
          message: 'Invalid destination',
          error: planError.message
        });
      }
    }

    // Préparer les arguments pour le workflow (format harmonisé avec l'API générique)
    const workflowArgs = {
      jobId,
      sourceType: detection.type,
      destinations,
      refinementPlans,
      maxItems: finalMaxItems,
      organizationId: workflowData.organizationId
    };

    // Add source according to type
    if (detection.type === 'url') {
      workflowArgs.sourceType = 'url';
      workflowArgs.url = detection.input;
    } else if (detection.type === 'file') {
      workflowArgs.sourceType = 'file';
      if (detection.mode === 'fileUploaded') {
        workflowArgs.fileId = detection.input;
        workflowArgs.filename = value.filename;
        if (!workflowArgs.filename) {
          return res.status(400).json({
            success: false,
            message: 'Validation error',
            error: 'filename is required when using fileId'
          });
        }
      }
    }

    // Clés LLM/Marker : JWT (utilisateur) ou HMAC + organizationId (appel interne).
    const isFileType = detection.type === 'file' || detection.type === 'url';
    const extractedConfig = await getWorkflowArgsConfig(req, detection.type, detection, isFileType, value.extractor?.browserProvider);

    workflowArgs.llmApiKey = extractedConfig.llmApiKey;
    if (extractedConfig.markerApiKey) {
      workflowArgs.markerApiKey = extractedConfig.markerApiKey;
    }
    if (extractedConfig.brightdataWs) {
      workflowArgs.brightdataWs = extractedConfig.brightdataWs;
    }

    await storeJobById(jobId, workflowArgs);
    const response = await axios.post(
      `${JOB_MANAGER_SERVICE_URL}/internal/pool/add`,
      {
        jobId,
        organizationId: workflowData.organizationId,
        workflowType: 'WorkflowTW',
        input: workflowArgs,
      },
      {
        timeout: 10000,
        headers: addInternalKey({ 'Content-Type': 'application/json' }, SERVICE_NAME),
      }
    );

    console.log(`[Extract] Job ${jobId} queued via job-manager-service, position: ${response.data.position}`);

    res.json({
      success: true,
      data: {
        jobId,
        status: 'pending',
        sourceType: detection.type,
        sseUrl: `/api/v1/jobs/${jobId}/status`,
        ...(detection.mode === 'fileUrl' && { fileUrl: detection.input }),
        ...(detection.mode === 'fileUploaded' && { fileId: detection.input }),
        ...(detection.mode === 'web' && { url: detection.input })
      }
    });

  } catch (error) {
    console.error('[WorkflowAPI] Extract error:', error);
    res.status(500).json({
      success: false,
      message: 'Error starting extraction',
      error: error.message
    });
  }
});
 
/**
 * POST /:organizationId/workflow/extract
 * Endpoint générique: toutes les informations de la config dans le body
 * 
 * Format extractor: { extractor: { type, url|fileUrl|fileId }, destination?: destination | [destination] }
 * Format input: { input: { content, source? }, destination?: destination | [destination] }
 * Le raffinage vient exclusivement de chaque destination (destination.refinement).
 */
app.post('/:organizationId/workflow/extract', async (req, res) => {
  try {
    const userId = await getUserIdFromRequest(req);
    const organizationId = getOrganizationIdFromRequest(req);
 
    // Vérifier la limite de tokens LLM avant de lancer le workflow
    const validationResult = schemas.extractWithSteps.validate(req.body);
    if (validationResult.error) {
      return res.status(400).json({
        success: false,
        message: 'Validation error',
        error: validationResult.error.details[0].message
      });
    }
    
    const { extractor, input, destination } = validationResult.value;
 
    // Normaliser la destination unique en liste (le crawler peut envoyer plusieurs)
    const destinations = Array.isArray(destination) ? destination : (destination ? [destination] : []);
 
    let workflowConfig;
 
    if (input) {
      workflowConfig = {
        sourceType: 'input',
        inputText: input.content,
        factsSourceUrl: input.source || null
      };
    } else {
      const { url, fileUrl, fileId, filename } = extractor;
      const detection = detectType({ url, fileUrl, fileId });
 
      if (fileId && !filename) {
        return res.status(400).json({
          success: false,
          message: 'Validation error',
          error: 'filename is required when using fileId in extractor'
        });
      }
 
      const extractorCfg = { ...(extractor.config || {}) };
      if (extractor.browserProvider) extractorCfg.browserProvider = extractor.browserProvider;
 
      if (detection.type === 'url') {
        workflowConfig = {
          sourceType: 'url',
          url: detection.input,
          extractorConfig: extractorCfg
        };
      } else {
        workflowConfig = {
          sourceType: 'file',
          fileId: detection.input,
          filename,
          extractorConfig: extractorCfg
        };
      }
    }
 
    const { sourceType, filename } = workflowConfig;
    const jobId = validationResult.value.idempotencyKey || uuidv4();
 
    const logDest = destinations?.length > 0 ? `+${destinations.length}dest` : '(extraction seule)';
    console.log(`[Extract] ${sourceType}${logDest}: ${jobId}`);
 
    // Résoudre le plan de raffinage à partir des destinations (fetch KB / APIs).
    // Le plafond d'items vient de chaque destination (refinement.spec) ; plus de repli au niveau workflow.
    let refinementPlans = [];
    if (destinations.length > 0) {
      try {
        refinementPlans = await buildRefinementPlans(destinations, {}, organizationId, undefined);
      } catch (planError) {
        return res.status(400).json({
          success: false,
          message: 'Invalid destination',
          error: planError.message
        });
      }
    }
 
    // Préparer les arguments pour le workflow Temporal
    const workflowArgs = {
      jobId,
      workflowId: null,
      destinations,
      refinementPlans,
      sourceType,
      extractorConfig: workflowConfig.extractorConfig || {},
      organizationId
    };
 
    // Gérer les différents types de source
    if (sourceType === 'input') {
      workflowArgs.inputText = workflowConfig.inputText;
      if (workflowConfig.factsSourceUrl) {
        workflowArgs.factsSourceUrl = workflowConfig.factsSourceUrl;
      }
    } else if (sourceType === 'url') {
      workflowArgs.url = workflowConfig.url;
    } else if (sourceType === 'file') {
      if (workflowConfig.fileId && filename) {
        workflowArgs.fileId = workflowConfig.fileId;
        workflowArgs.filename = filename;
        if (!filename) {
          return res.status(400).json({
            success: false,
            message: 'Validation error',
            error: 'filename is required when using fileId'
          });
        }
      }
    }
 
    // Fetch API keys using config or config-service
    // For sourceType 'url', we don't know yet if it's a file (resolveUrl will tell us),
    // so always fetch both LLM and Marker keys
    const isFileType = sourceType === 'url' || sourceType === 'file';
    const extractedConfig = await getWorkflowArgsConfig(req, sourceType, null, isFileType, extractor?.browserProvider);
 
    workflowArgs.llmApiKey = extractedConfig.llmApiKey;
    // Plus de modèle au niveau du workflow : le modèle est porté par chaque plan de
    // raffinage (destination.refinement.llmModel).
    if (extractedConfig.markerApiKey) {
      workflowArgs.markerApiKey = extractedConfig.markerApiKey;
    }
    if (extractedConfig.brightdataWs) {
      workflowArgs.brightdataWs = extractedConfig.brightdataWs;
    }
 
    await storeJobById(jobId, workflowArgs);
    const response = await axios.post(
      `${JOB_MANAGER_SERVICE_URL}/internal/pool/add`,
      {
        jobId,
        organizationId,
        workflowType: 'WorkflowTW',
        input: workflowArgs,
      },
      {
        timeout: 10000,
        headers: addInternalKey({ 'Content-Type': 'application/json' }, SERVICE_NAME),
      }
    );
 
    console.log(`[Extract] Job ${jobId} queued via job-manager-service, position: ${response.data.position}`);
 
    // Construire la réponse
    const responseData = {
      jobId,
      status: 'pending',
      sourceType,
      hasDestinations: destinations.length > 0,
      sseUrl: `/api/v1/jobs/${jobId}/status`
    };
    
    if (sourceType === 'input') {
      const inputTextValue = workflowConfig.inputText || '';
      responseData.input = inputTextValue.substring(0, 100) + (inputTextValue.length > 100 ? '...' : '');
    } else if (sourceType === 'url') {
      responseData.url = workflowConfig.url;
    } else if (sourceType === 'file' && workflowConfig.fileId) {
      responseData.fileId = workflowConfig.fileId;
    }
 
    res.json({
      success: true,
      data: responseData
    });
 
  } catch (error) {
    console.error('[WorkflowAPI] Generic extract error:', error);
    res.status(500).json({
      success: false,
      message: 'Error starting extraction',
      error: error.message
    });
  }
});
 
// ============================================================================
// Start Server
// ============================================================================
 
app.listen(PORT, () => {
  console.log(`🚀 Workflow API running on port ${PORT}`);
  console.log(`📋 Task queue: ${config.temporalTaskQueue}`);
  console.log(`🏥 Health check: http://localhost:${PORT}/health`);
});
 
module.exports = app;