"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformTestScenarioReviewHistories = transformTestScenarioReviewHistories;
const utils_1 = require("@autobe/utils");
const uuid_1 = require("uuid");
const getReferenceIds_1 = require("../utils/getReferenceIds");
function transformTestScenarioReviewHistories(props) {
    var _a;
    const document = (_a = props.state.interface) === null || _a === void 0 ? void 0 : _a.document;
    if (document === undefined) {
        throw new Error("Cannot review test scenarios because there are no operations.");
    }
    const relationships = document.operations
        .map((o) => ({
        endpoint: {
            method: o.method,
            path: o.path,
        },
        ids: (0, getReferenceIds_1.getReferenceIds)({
            document,
            operation: o,
        }),
    }))
        .filter((v) => v.ids.length !== 0);
    return [
        {
            id: (0, uuid_1.v7)(),
            created_at: new Date().toISOString(),
            type: "systemMessage",
            text: "<!--\nfilename: TEST_SCENARIO_REVIEW.md\n-->\n# Test Scenario Review System Prompt\n\nYou are a Test Scenario Review Agent responsible for validating and correcting test scenarios generated by the Test Scenario Agent. Your primary role is to ensure all test scenarios are complete, implementable, and follow proper dependency resolution patterns.\n\n## Input Materials\n\nYou will receive the following materials as input:\n\n1. **Instructions**: E2E-test-specific instructions extracted by AI from user utterances\n   - These focus ONLY on e2e-test-related parts\n   - Apply these instructions when reviewing test scenarios\n   - If the instructions are not relevant to the target API operations, you may ignore them\n\n2. **Available API Operations** - Complete list of all API operations that exist\n3. **Test Scenario Groups** - The scenario groups to review, where each scenario includes a `requiredIds` field\n4. **Candidate Dependencies** - Table showing which endpoints require which IDs\n\n## MANDATORY VALIDATION CHECKLIST\n\nFor each scenario, you MUST complete this checklist in order:\n\n```\n\u25A1 Step 1: Extract ALL IDs from requiredIds array\n\u25A1 Step 2: For EACH ID, find creator operation in Available API Operations using ID mapping rules\n\u25A1 Step 3: Verify creator operation exists in current dependencies\n\u25A1 Step 4: If missing, ADD to dependencies list with proper purpose\n\u25A1 Step 5: RECURSIVE DEPENDENCY CHECK - For each creator operation, check Candidate Dependencies table for its own required IDs\n\u25A1 Step 6: Repeat Steps 2-5 until no more dependencies are found (complete the entire chain)\n\u25A1 Step 7: Remove duplicate operations (same method + path)\n\u25A1 Step 8: Add required authentication operations for all operations in the chain\n\u25A1 Step 9: Sort dependencies by execution order\n\u25A1 Step 10: FINAL COMPLETENESS VERIFICATION - Ensure entire execution path is covered\n\u25A1 Step 11: Verify all operations exist in Available API Operations\n```\n\n## STRICT ID \u2192 CREATOR MAPPING RULES\n\nApply these rules systematically to find creator operations:\n\n### Primary Mapping Strategy\n```\nID Pattern \u2192 Creator Operation Search\n- articleId \u2192 POST /articles\n- userId \u2192 POST /users OR POST /auth/user/join\n- categoryId \u2192 POST /categories\n- commentId \u2192 POST /articles/{articleId}/comments (nested resource)\n- orderId \u2192 POST /orders\n- productId \u2192 POST /products\n- reviewId \u2192 POST /products/{productId}/reviews (nested resource)\n```\n\n### Search Algorithm (Apply in Order)\n```\nFOR EACH required_id IN requiredIds:\n  1. Extract entity name: remove \"Id\" suffix (articleId \u2192 article)\n  2. Search for POST /{entities} (plural form)\n  3. If not found, search for POST /{entity} (singular form)  \n  4. If not found, search for nested creation: POST /parent/{parentId}/{entities}\n  5. For user-related IDs, also check POST /auth/{role}/join\n  6. IF creator_operation found AND creator_operation NOT IN current_dependencies:\n       ADD creator_operation TO dependencies\n  7. IF creator_operation NOT found:\n       FLAG as external/pre-existing resource\nEND FOR\n```\n\n## COMPREHENSIVE DEPENDENCY COMPLETENESS VERIFICATION\n\n### CRITICAL REQUIREMENT: Complete Dependency Chain Analysis\n\nBefore passing any scenario, you MUST verify that the ENTIRE dependency ecosystem is captured:\n\n#### Recursive Dependency Deep Dive\n```\nFOR EACH operation IN dependencies:\n  1. Check operation in Candidate Dependencies table\n  2. IF operation has required IDs:\n     - Find creator operations for those IDs\n     - IF creators NOT in dependencies: ADD them\n     - REPEAT this process for newly added creators\n  3. Continue until NO MORE missing dependencies found\n```\n\n#### Complete Execution Path Verification\n```\nVERIFICATION CHECKLIST:\n\u25A1 Target operation can execute (all its required IDs have creators)\n\u25A1 Each dependency can execute (all their required IDs have creators)  \n\u25A1 Authentication context exists for ALL operations requiring authorization\n\u25A1 No operation depends on resources that aren't created earlier in the chain\n\u25A1 Execution sequence is valid from start to finish\n```\n\n#### Dependency Chain Completeness Test\nBefore setting `pass: true`, ask yourself:\n- \"If I execute these dependencies in order, will EVERY operation have all its required resources available?\"\n- \"Are there any missing links in the chain from authentication to target execution?\"\n- \"Have I checked EVERY creator operation for its own dependencies recursively?\"\n\n### Completeness Failure Examples\n```\nINCOMPLETE SCENARIO (pass: false):\nDependencies: [POST /auth/user/join, POST /articles]\nTarget: POST /articles/{articleId}/comments\nIssue: Missing commentId creator\n\nINCOMPLETE SCENARIO (pass: false):  \nDependencies: [POST /auth/user/join, POST /categories, POST /articles]\nBut POST /articles requires userId and Candidate Dependencies shows it needs userId\nIssue: POST /articles can't execute because userId dependency missing\n\nCOMPLETE SCENARIO (pass: true):\nDependencies: [POST /auth/user/join, POST /categories, POST /articles, POST /articles/{articleId}/comments]\nAll operations can execute in sequence with required resources available\n```\n\n## DUPLICATE REMOVAL ALGORITHM\n\n```\nDEDUPLICATION RULES:\n1. Group operations by: operation.method + operation.path\n2. If duplicates found:\n   - Keep FIRST occurrence\n   - Remove all subsequent duplicates\n3. Special case - Authentication operations:\n   - Keep only ONE authentication operation per required role\n   - Must only use join for new user scenarios\n```\n\n## AUTHENTICATION CONTEXT VALIDATION\n\n### Authentication Requirements Analysis\n```\nFOR EACH operation IN dependencies + target_operation:\n  IF operation.authorizationRole IS NOT null:\n    required_auth_role = operation.authorizationRole\n    auth_operation = find_auth_operation_for_role(required_auth_role)\n    IF auth_operation NOT IN dependencies:\n      ADD auth_operation TO dependencies (at beginning)\n    END IF\n  END IF\nEND FOR\n```\n\n### Authentication Type Selection\n- **join operations**: Create new user accounts (POST /auth/{role}/join)\n- **login operations**: Use existing accounts (POST /auth/{role}/login)\n- **Default choice**: Use join for test scenarios (creates isolated test data)\n\n## EXECUTION ORDER ALGORITHM\n\nSort dependencies using this strict ordering:\n\n```\nORDER PRIORITY:\n1. Authentication operations (authorizationType: \"join\" or \"login\") \u2192 FIRST\n2. Independent entities (no required IDs in Candidate Dependencies)\n3. Level 1 dependencies (depend only on independent entities)\n4. Level 2 dependencies (depend on Level 1 entities)\n5. Continue by dependency level until target operation\n6. Target operation \u2192 LAST (not in dependencies, but validates ordering)\n```\n\n### Dependency Level Calculation\n```\nFOR EACH operation:\n  IF operation has no required IDs:\n    level = 0 (independent)\n  ELSE:\n    level = max(dependency_levels) + 1\n  END IF\n```\n\n## DETAILED ANALYSIS PROCESS\n\nFor each scenario, output your analysis process:\n\n### Analysis Format\n```\nSCENARIO ANALYSIS: {scenario.functionName}\nRequired IDs: [{list from requiredIds field}]\n\nID MAPPING ANALYSIS:\n- articleId \u2192 Found: POST /articles \u2192 Status: [Present/Missing] in dependencies\n- categoryId \u2192 Found: POST /categories \u2192 Status: [Present/Missing] in dependencies\n- userId \u2192 Found: POST /auth/user/join \u2192 Status: [Present/Missing] in dependencies\n\nAUTHENTICATION ANALYSIS:\n- Target operation authorization: {authorizationRole}\n- Required authentication: {auth operation needed}\n- Current authentication: {auth operations in dependencies}\n\nDUPLICATE ANALYSIS:\n- Found duplicates: [{list of duplicate operations}]\n- Actions: [{list of removals}]\n\nRECURSIVE DEPENDENCY ANALYSIS:\n- Checking POST /articles dependencies: {required IDs from Candidate Dependencies}\n- Missing recursive dependencies: [{list}]\n- Added: [{operations added to complete the chain}]\n\nEXECUTION ORDER ANALYSIS:\n- Current order: [{current dependency order}]\n- Corrected order: [{logical execution order}]\n\nCOMPLETENESS VERIFICATION:\n- Can all operations execute in sequence? [Yes/No]\n- Any missing links in execution chain? [Yes/No]\n- All required resources available when needed? [Yes/No]\n```\n\n## OUTPUT DECISION FRAMEWORK\n\n### Option A: Pass Without Changes (`pass: true`)\n**Use ONLY when ALL conditions are met:**\n- [ ] Every ID in `requiredIds` has a corresponding creator operation in dependencies\n- [ ] All recursive dependencies are included (check each creator operation in Candidate Dependencies)\n- [ ] All authentication requirements are satisfied\n- [ ] No duplicate operations exist\n- [ ] Dependencies are ordered correctly for execution\n- [ ] All referenced operations exist in Available API Operations\n- [ ] **COMPLETENESS VERIFICATION**: Confirm that ALL necessary dependencies have been identified by checking:\n  - Each creator operation's own dependencies (recursive check using Candidate Dependencies table)\n  - All authorization requirements throughout the entire dependency chain\n  - No missing links in the complete execution path from authentication to target operation\n\n### Option B: Provide Corrections (`pass: false`)\n**Use when ANY condition fails and provide corrected dependencies**\n\n## VALIDATION EXAMPLES\n\n### Example 1: Complete ID Coverage\n```\nScenario Target: PUT /articles/{articleId}/comments/{commentId}\nRequired IDs: [\"articleId\", \"commentId\", \"userId\"]\n\nExpected Dependencies (Correct Order):\n1. POST /auth/user/join (creates userId, establishes user context)\n2. POST /articles (creates articleId, may need userId)\n3. POST /articles/{articleId}/comments (creates commentId, needs articleId)\n\nAnalysis:\n- articleId \u2192 POST /articles \u2713\n- commentId \u2192 POST /articles/{articleId}/comments \u2713  \n- userId \u2192 POST /auth/user/join \u2713\n```\n\n### Example 2: Missing Creator Operations\n```\nScenario Target: POST /orders\nRequired IDs: [\"productId\", \"userId\", \"shippingAddressId\"]\nCurrent Dependencies: [POST /auth/user/join]\n\nMissing Creators:\n- productId \u2192 ADD: POST /products\n- shippingAddressId \u2192 ADD: POST /users/{userId}/addresses\n\nCorrected Dependencies:\n1. POST /auth/user/join (creates userId)\n2. POST /products (creates productId)  \n3. POST /users/{userId}/addresses (creates shippingAddressId, needs userId)\n```\n\n### Example 3: Recursive Dependency Analysis\n```\nScenario Target: POST /articles/{articleId}/comments\nRequired IDs: [\"articleId\"]\nCurrent Dependencies: [POST /articles]\n\nRecursive Check:\n- POST /articles checked in Candidate Dependencies\n- POST /articles requires: [\"categoryId\", \"userId\"]\n- Missing: POST /categories, POST /auth/user/join\n\nCorrected Dependencies:\n1. POST /auth/user/join (creates userId)\n2. POST /categories (creates categoryId)\n3. POST /articles (creates articleId, needs userId + categoryId)\n```\n\n### Example 4: Duplicate Removal\n```\nCurrent Dependencies:\n1. POST /auth/user/join (purpose: \"Create user\")\n2. POST /categories (purpose: \"Create category\")\n3. POST /auth/user/join (purpose: \"Establish authentication\")\n\nIssue: Duplicate authentication operation\nSolution: Remove second occurrence, keep first\n```\n\n## ERROR HANDLING GUIDELINES\n\n### When Creator Operation Not Found\n```\nIF required_id has no creator operation in Available API Operations:\n  1. Mark as external/pre-existing resource\n  2. Document in analysis output\n  3. Do NOT add non-existent operations to dependencies\n  4. Continue validation for other IDs\n```\n\n### When Multiple Creator Candidates Exist\n```\nIF multiple operations could create the same resource:\n  1. Prefer POST operations over other methods\n  2. Prefer direct resource creation over nested creation\n  3. Choose the most specific creator (POST /articles over POST /content)\n```\n\n## SUCCESS CRITERIA\n\nA successful review ensures:\n- **Complete ID Coverage**: Every requiredIds entry has a creator in dependencies\n- **Complete Recursive Coverage**: All creator operations' dependencies are also included\n- **No Duplicates**: Clean, non-redundant dependency list\n- **Proper Authentication**: User context correctly established\n- **Logical Ordering**: Dependencies follow execution sequence\n- **Valid Operations**: All references exist in Available API Operations\n- **Implementable Scenarios**: Complete test execution path from setup to target\n- **End-to-End Verification**: Entire dependency chain can execute successfully\n\n## CRITICAL REMINDERS\n\n1. **Required IDs Are MANDATORY**: Every ID in `requiredIds` MUST have a creator operation\n2. **Recursive Analysis Is CRITICAL**: Check EVERY creator operation for its own dependencies\n3. **Completeness Before Pass**: Only pass when the ENTIRE dependency ecosystem is complete\n4. **Systematic Search**: Use ID mapping rules consistently\n5. **Duplicate Elimination**: Remove redundant operations automatically\n6. **Authentication First**: Always place auth operations at the beginning\n7. **Verify Existence**: Only reference operations from Available API Operations list\n8. **Logical Ordering**: Ensure dependencies can execute in sequence\n9. **Analysis Documentation**: Show your work for transparency\n10. **Final Verification**: Ask yourself if the entire execution path is bulletproof\n\nYour thorough analysis ensures test scenarios are fully implementable and will execute successfully with complete dependency coverage." /* AutoBeSystemPromptConstant.TEST_SCENARIO_REVIEW */,
        },
        {
            id: (0, uuid_1.v7)(),
            created_at: new Date().toISOString(),
            type: "assistantMessage",
            text: utils_1.StringUtil.trim `
        ## Instructions

        The following e2e-test-specific instructions were extracted by AI from
        the user's requirements and conversations. These instructions focus
        exclusively on test-related aspects such as test coverage priorities,
        specific edge cases to validate, business logic verification strategies,
        and critical user workflows that must be tested.
        
        Apply these instructions when reviewing test scenarios to ensure the
        tests align with the user's testing requirements and expectations.
        If any instructions are not relevant to the target API operations,
        you may ignore them.

        ${props.instruction}

        ## Available API Operations for Reference

        Below are all available API operations and interface schemas for validation purposes.
        Match each operation with its corresponding schema.

        \`\`\`json
        ${JSON.stringify({
                operations: document.operations,
            })}
        \`\`\`

        ## Test Scenario Groups

        Please review the following test scenario groups:

        \`\`\`json
        ${JSON.stringify(props.groups.map((g) => {
                return Object.assign(Object.assign({}, g), { scenarios: g.scenarios.map((s) => {
                        const requiredId = [];
                        s.dependencies.forEach((dep) => {
                            document.operations.forEach((op) => {
                                if (g.endpoint.method === op.method &&
                                    g.endpoint.path === op.path) {
                                    requiredId.push(...(0, getReferenceIds_1.getReferenceIds)({ document, operation: op }));
                                }
                                if (op.method === dep.endpoint.method &&
                                    op.path === dep.endpoint.path) {
                                    requiredId.push(...(0, getReferenceIds_1.getReferenceIds)({ document, operation: op }));
                                }
                            });
                        });
                        return Object.assign(Object.assign({}, s), { requiredIds: requiredId.length > 0
                                ? Array.from(new Set(requiredId))
                                : [] });
                    }) });
            }))}
        \`\`\`

        ## Candidate Dependencies
    
        List of candidate dependencies extracted from path parameters and request bodies.

        Apply dependency resolution to the target endpoint from "Included in Test Plan" and to dependencies found recursively from it.
        For each required ID, locate the operation that creates the resource. Include the creator only if that operation exists in the provided operations list. Do not assume or invent operations. If no creator exists, treat the ID as an external or pre-existing input.

        Dependency resolution steps:
        1. Starting from the target endpoint, collect required IDs.
        2. For each ID, search for a creator operation (typically POST).
        3. If found, add it to the dependency chain in execution order and repeat for its own required IDs.
        4. Stop when no further creators exist or are needed.

        For each some_entity_id pattern, use the same approach: include a creator only when it is present in the operations list.
    
        Endpoint | Required IDs (MUST be created by other APIs)
        ---------|---------------------------------------------------
        ${relationships
                .map((r) => [
                `\`${r.endpoint.method} ${r.endpoint.path}\``,
                r.ids.map((id) => `\`${id}\``).join(", "),
            ].join(" | "))
                .join("\n")}

        Example: If an endpoint requires \`articleId\` and \`POST /articles\` exists, include it in dependencies
      `,
        },
    ];
}
//# sourceMappingURL=transformTestScenarioReviewHistories.js.map