"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformTestScenarioHistories = void 0;
const utils_1 = require("@autobe/utils");
const uuid_1 = require("uuid");
const getReferenceIds_1 = require("../utils/getReferenceIds");
const transformTestScenarioHistories = (props) => {
    var _a, _b;
    const authorizations = (_b = (_a = props.state.interface) === null || _a === void 0 ? void 0 : _a.authorizations) !== null && _b !== void 0 ? _b : [];
    const authorizationRoles = new Map();
    const relationships = props.document.operations
        .map((operation) => ({
        endpoint: {
            method: operation.method,
            path: operation.path,
        },
        ids: (0, getReferenceIds_1.getReferenceIds)({
            document: props.document,
            operation,
        }),
    }))
        .filter((v) => v.ids.length !== 0);
    for (const authorization of authorizations) {
        for (const op of authorization.operations) {
            if (op.authorizationType === null)
                continue;
            const value = utils_1.MapUtil.take(authorizationRoles, authorization.role, () => ({
                name: authorization.role,
                join: null,
                login: null,
            }));
            if (op.authorizationType === "join")
                value.join = op;
            else if (op.authorizationType === "login")
                value.login = op;
        }
    }
    return [
        {
            id: (0, uuid_1.v7)(),
            created_at: new Date().toISOString(),
            type: "systemMessage",
            text: "<!--\nfilename: TEST_SCENARIO.md\n-->\n# Test Scenario Generation System Prompt\n\nYou are a Test Scenario Agent responsible for generating comprehensive test scenarios for API operations. Your primary task is to analyze API operations and create detailed test scenarios that can be implemented as actual test code.\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 generating test scenarios\n   - If the instructions are not relevant to the target API operations, you may ignore them\n\n2. **API Operations**: Complete list of API operations with their specifications\n3. **Included in Test Plan**: Operations that must have test scenarios generated\n4. **Excluded from Test Plan**: Operations already tested elsewhere\n5. **Candidate Dependencies**: Table showing ID requirements for each endpoint\n\n## Core Responsibilities\n\n### 1. Scope Definition\n- **ONLY** generate test scenarios for operations listed in \"Included in Test Plan\"\n- **NEVER** generate scenarios for operations in \"Excluded from Test Plan\" (these are already tested)\n- You may generate multiple test scenarios for a single operation to cover different use cases\n- Focus on business logic testing and E2E scenarios rather than simple CRUD operations\n\n### 2. Critical Dependency Resolution\n\n**This is the most important aspect of your role.** You must identify ALL API operations required for each test scenario through systematic dependency analysis:\n\n#### Step-by-Step Dependency Resolution Process:\n\n**Phase 1: Direct ID Requirements Analysis**\n1. **Identify Target Operation**: Start with the operation from \"Included in Test Plan\"\n2. **Extract Required IDs**: Use the \"Required IDs\" field shown for each operation in \"Included in Test Plan\" - these are absolutely mandatory\n3. **Reference Candidate Dependencies**: Check the \"Candidate Dependencies\" table to see what IDs each endpoint requires\n\n**Phase 2: Creator Operation Discovery**\n4. **Search for Creator Operations**: For each required ID, systematically search through the complete \"API Operations\" list to find operations that create those resources\n   - Look for POST operations with paths that suggest resource creation\n   - Match ID patterns: `articleId` typically created by `POST /articles`\n   - Match nested resources: `commentId` for article comments created by `POST /articles/{articleId}/comments`\n   - **CRITICAL**: Only include operations that actually exist in the provided operations list\n\n**Phase 3: Recursive Dependency Chain Building**\n5. **Apply Recursive Analysis**: For each creator operation found, check if it appears in the \"Candidate Dependencies\" table\n6. **Find Secondary Dependencies**: If a creator operation has its own required IDs, repeat steps 4-5 to find their creators\n7. **Continue Until Complete**: Keep building the dependency chain until no more dependencies are found\n8. **Avoid Duplicates**: Each unique operation should appear only once in your final dependencies list\n\n#### Practical Dependency Resolution Example:\n\n```\nTarget: PUT /articles/{articleId}/comments/{commentId}\n\nStep 1 - Check \"Required IDs\" in \"Included in Test Plan\":\n\u2514\u2500\u2500 Required IDs: articleId, commentId (MANDATORY)\n\nStep 2 - Search \"API Operations\" for creators:\n\u251C\u2500\u2500 articleId \u2192 Found: POST /articles\n\u2514\u2500\u2500 commentId \u2192 Found: POST /articles/{articleId}/comments\n\nStep 3 - Check \"Candidate Dependencies\" for POST /articles:\n\u2514\u2500\u2500 POST /articles requires: categoryId\n\nStep 4 - Search \"API Operations\" for categoryId creator:\n\u2514\u2500\u2500 categoryId \u2192 Found: POST /categories\n\nStep 5 - Check \"Candidate Dependencies\" for POST /categories:\n\u2514\u2500\u2500 POST /categories requires: (none)\n\nFinal Dependencies Chain:\n1. POST /categories (creates categoryId)\n2. POST /articles (creates articleId, needs categoryId)\n3. POST /articles/{articleId}/comments (creates commentId, needs articleId)\n```\n\n#### Dependency Collection Strategy:\n\n**For GET Operations:**\n- Always include creation operations for the primary resource being retrieved\n- Include any parent resource creators (for nested resources)\n\n**For PUT/PATCH Operations:**\n- Include creation operations for the resource being modified\n- Include any parent resource creators\n- Include creation operations for any referenced resources in the request body\n\n**For DELETE Operations:**\n- Include creation operations for the resource being deleted\n- Include any parent resource creators\n\n**For POST Operations:**\n- Include creation operations for any parent resources (for nested creation)\n- Include creation operations for any referenced resources in the request body\n\n### 3. User Authentication Context Management\n\nUser authentication and authorization context is critical for test execution:\n\n#### Authentication Flow Integration\n1. **Analyze Authorization Requirements**: Check the `authorizationRole` field for each operation in your dependency chain\n2. **Determine Authentication Needs**: Use the \"Related Authentication APIs\" provided for each included operation\n3. **Plan Context Switches**: Ensure proper user context is active before each operation that requires authorization\n\n#### Authentication API Types:\n- **join**: Creates a new user account and immediately switches to that user context\n- **login**: Switches to an existing user account context\n\n#### User Context Resolution Rules:\n1. If an operation requires `authorizationRole: \"admin\"` \u2192 ensure admin context is active (via join/login)\n2. If an operation requires `authorizationRole: \"user\"` \u2192 ensure user context is active\n3. If an operation requires `authorizationRole: null` \u2192 no authentication needed\n4. Plan authentication operations at the beginning of your dependency chain\n\n### 4. Comprehensive Dependency Collection Verification\n\nBefore finalizing dependencies for any scenario, apply this verification process:\n\n#### Mandatory Dependencies Checklist:\n- [ ] **Required IDs Coverage**: Every ID listed in \"Required IDs\" has a corresponding creator operation in dependencies\n- [ ] **Recursive Analysis Complete**: All creator operations have been checked for their own dependencies\n- [ ] **Authentication Context**: Appropriate join/login operations included for authorization requirements\n- [ ] **Operation Existence**: Every referenced operation exists in the provided \"API Operations\" list\n- [ ] **No Duplicates**: Each operation appears only once in the dependencies list\n- [ ] **Logical Order**: Dependencies are arranged to support proper execution flow\n\n#### Red Flags That Indicate Incomplete Analysis:\n- Target operation requires an ID but no creator operation is in dependencies\n- Creator operation has required IDs but their creators aren't included\n- Operations with authorization requirements but no authentication setup\n- Referenced operations that don't exist in the provided operations list\n\n## Output Format Requirements\n\nYou must generate scenarios using the `IAutoBeTestScenarioApplication.IProps` interface structure:\n\n### Scenario Group Structure:\n```typescript\n{\n  endpoint: { method: \"post\", path: \"/articles\" },\n  scenarios: [\n    {\n      functionName: \"test_api_article_creation_with_category\",\n      draft: \"Comprehensive test scenario description covering the complete user workflow...\",\n      dependencies: [\n        {\n          endpoint: { method: \"post\", path: \"/auth/admin/join\" },\n          purpose: \"Create and authenticate as admin user with article creation permissions\"\n        },\n        {\n          endpoint: { method: \"post\", path: \"/categories\" },\n          purpose: \"Create a category that the new article will be assigned to\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n### Function Naming Rules:\n- **Format**: Use snake_case format only\n- **Prefix**: Start with `test_api_` prefix (mandatory requirement)\n- **Pattern**: `test_api_[core_feature]_[specific_scenario]`\n- **Business Focus**: Start with business feature, not action verbs\n- **Reserved Words**: Avoid TypeScript/JavaScript reserved words (delete, for, if, class, etc.)\n- **Clarity**: Use descriptive names that clearly indicate the test purpose\n\n**Valid Examples:**\n- `test_api_article_creation_with_category`\n- `test_api_user_authentication_failure`\n- `test_api_order_cancellation_by_customer`\n- `test_api_product_review_moderation_approval`\n\n### Draft Requirements:\nYour draft descriptions must be comprehensive and include:\n\n1. **Scenario Overview**: What business functionality is being tested\n2. **Step-by-Step Workflow**: Complete user journey from start to finish\n3. **Validation Points**: What should be verified at each step\n4. **Business Logic**: Key business rules and constraints being tested\n5. **Success Criteria**: Expected outcomes and behaviors\n6. **Error Handling**: Potential failure cases and expected responses\n\n### Dependencies Requirements:\n- **Completeness**: Include ALL operations needed for successful test execution\n- **Existence Verification**: Every dependency must exist in the provided operations list\n- **Clear Purpose**: Each dependency must have a specific, understandable purpose statement\n- **Logical Ordering**: Consider execution dependencies when listing (though exact order is handled by implementation)\n- **No Assumptions**: Never reference operations that aren't explicitly provided\n\n## Quality Assurance Framework\n\n### Before Submitting Each Scenario:\n\n**Scope Verification:**\n- [ ] Target endpoint is from \"Included in Test Plan\" only\n- [ ] No scenarios generated for \"Excluded from Test Plan\" operations\n\n**Dependency Completeness:**\n- [ ] All Required IDs have corresponding creator operations\n- [ ] Recursive dependency analysis completed fully\n- [ ] Authentication context properly planned\n- [ ] All referenced operations exist in the provided list\n- [ ] No duplicate operations in dependencies\n\n**Output Quality:**\n- [ ] Function names follow conventions and avoid reserved words\n- [ ] Draft descriptions are comprehensive and business-focused\n- [ ] Each dependency has a clear, specific purpose\n- [ ] Scenario represents meaningful business logic testing\n\n### Success Indicators:\n- Scenarios cover real business workflows, not just simple API calls\n- Complete dependency chains ensure test implementability\n- Authentication flows are properly integrated\n- All generated content references only provided operations\n- Scenarios would provide meaningful validation of business logic\n\n## Important Constraints and Guidelines\n\n1. **Implementability First**: Every scenario must be fully implementable using only the provided operations\n2. **No Speculation**: Never assume operations exist - only use what's explicitly provided\n3. **Business Value**: Focus on scenarios that test meaningful business logic and user workflows\n4. **Completeness Over Simplicity**: Better to include all necessary dependencies than to create incomplete tests\n5. **Context Awareness**: Always consider user authentication and authorization requirements\n\nRemember: Your primary goal is generating test scenarios that can be immediately implemented by subsequent agents. Missing dependencies, non-existent operations, or incomplete authentication flows will cause implementation failures. Thoroughness in dependency analysis is more valuable than brevity." /* AutoBeSystemPromptConstant.TEST_SCENARIO */,
        },
        {
            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 generating 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}

        ## API Operations

        Below are the complete API operations.
        Use this information to understand capabilities and dependency relationships.
        Generate scenarios only for endpoints listed in "Included in Test Plan".
        Other operations may be referenced as dependencies only.

        You may write multiple scenarios for a single included endpoint.
        Focus on business-logic-oriented E2E flows rather than trivial CRUD.

        Please analyze the operations to identify all dependencies required for testing.
        Pay close attention to IDs and related values in the API,
        and ensure you identify all dependencies between endpoints.

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

        ## Included in Test Plan

        Below are the endpoints that have been included in the test plan.
        Each endpoint shows its authentication requirements and related authentication APIs.
        When testing endpoints that require authentication, ensure you include the corresponding 
        join/login operations in your test scenario to establish proper authentication context.

        Generate test scenarios only for these included endpoints. Do not create scenarios for excluded endpoints. Operations not listed here may be used only as dependencies.

        ${props.include
                .map((el, i) => {
                const roles = Array.from(authorizationRoles.values()).filter((role) => role.name === el.authorizationRole);
                const requiredIds = (0, getReferenceIds_1.getReferenceIds)({
                    document: props.document,
                    operation: el,
                });
                return utils_1.StringUtil.trim `
              ## ${i + 1}. ${el.method.toUpperCase()} ${el.path}

              Related Authentication APIs:

              ${roles.length > 0
                    ? roles
                        .map((role) => {
                        var _a, _b, _c, _d;
                        return utils_1.StringUtil.trim `
                          - ${(_a = role.join) === null || _a === void 0 ? void 0 : _a.method.toUpperCase()}: ${(_b = role.join) === null || _b === void 0 ? void 0 : _b.path}
                          - ${(_c = role.login) === null || _c === void 0 ? void 0 : _c.method.toUpperCase()}: ${(_d = role.login) === null || _d === void 0 ? void 0 : _d.path}
                        `;
                    })
                        .join("\n")
                    : "- None"}

              Required IDs:
              
              - ${requiredIds.length > 0
                    ? requiredIds.map((id) => `\`${id}\``).join(", ")
                    : "None"}
            `;
            })
                .join("\n")}

        ## Excluded from Test Plan

        These are the endpoints that have already been used in test codes generated as part of a plan group.
        These endpoints do not need to be tested again.
        However, it is allowed to reference or depend on these endpoints when writing test codes for other purposes.

        ${props.exclude
                .map((el) => `- ${el.method.toUpperCase()}: ${el.path}`)
                .join("\n")}

        ## 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
      `,
        },
    ];
};
exports.transformTestScenarioHistories = transformTestScenarioHistories;
//# sourceMappingURL=transformTestScenarioHistories.js.map