"use strict";
/**
 * Frontend Unit Test Generator
 * Generates React Testing Library tests for frontend components
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrontendTestGenerator = void 0;
const path = __importStar(require("path"));
class FrontendTestGenerator {
    id = 'frontend-unit-tests';
    name = 'Frontend Unit Test Generator';
    description = 'Generates React Testing Library unit tests';
    testFramework = 'vitest';
    generate(context) {
        const { workflow, outputDirectory } = context;
        const files = [];
        if (!workflow.testing?.unit_tests) {
            return { files: [] };
        }
        // Filter unit tests for frontend components
        const frontendTests = workflow.testing.unit_tests.filter(test => {
            const [componentName] = test.component.split('.');
            const component = workflow.stack[componentName];
            return component?.type === 'frontend';
        });
        for (const test of frontendTests) {
            const [componentName, componentId] = test.component.split('.');
            const stackComponent = workflow.stack[componentName];
            if (!stackComponent)
                continue;
            // Find the specific component definition
            const component = stackComponent.components?.find(c => c.id === componentId);
            if (!component)
                continue;
            // Generate test file
            files.push(this.generateComponentTest(componentName, component, test.scenarios, stackComponent.technology, outputDirectory));
        }
        // Generate test setup file
        if (files.length > 0) {
            const frontendComponent = Object.entries(workflow.stack).find(([_, c]) => c.type === 'frontend');
            if (frontendComponent) {
                files.push(this.generateTestSetup(frontendComponent[0], outputDirectory));
                files.push(this.generateVitestConfig(frontendComponent[0], outputDirectory));
            }
        }
        return { files };
    }
    generateComponentTest(stackComponentName, component, scenarios, technology, outputDir) {
        const componentName = component.name;
        const isReact = technology === 'react';
        let content = `import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { ${componentName} } from './${componentName}';

describe('${componentName}', () => {
`;
        // Generate test cases for each scenario
        for (const scenario of scenarios) {
            content += this.generateScenarioTest(scenario, component, isReact);
        }
        content += `});
`;
        return {
            path: path.join(outputDir, stackComponentName, 'src', 'components', `${componentName}.test.tsx`),
            content,
            overwrite: true,
        };
    }
    generateScenarioTest(scenario, component, _isReact) {
        const lowerScenario = scenario.toLowerCase();
        // Check for common test patterns and generate appropriate tests
        if (lowerScenario.includes('validation') && lowerScenario.includes('empty')) {
            return this.generateEmptyValidationTest(component);
        }
        if (lowerScenario.includes('loading state') || lowerScenario.includes('loading')) {
            return this.generateLoadingStateTest(component);
        }
        if (lowerScenario.includes('error') || lowerScenario.includes('api error')) {
            return this.generateErrorDisplayTest(component);
        }
        if (lowerScenario.includes('submit') || lowerScenario.includes('submission')) {
            return this.generateSubmissionTest(component);
        }
        // Generic test case
        return `  it('${scenario}', async () => {
    render(<${component.name} />);

    // TODO: Implement test for: ${scenario}
    expect(true).toBe(true);
  });

`;
    }
    generateEmptyValidationTest(component) {
        return `  it('displays validation errors for empty fields', async () => {
    render(<${component.name} />);

    const submitButton = screen.getByRole('button', { name: /submit|log in|sign in/i });
    fireEvent.click(submitButton);

    await waitFor(() => {
      expect(screen.getByText(/required|fill in/i)).toBeInTheDocument();
    });
  });

`;
    }
    generateLoadingStateTest(component) {
        return `  it('shows loading state during submission', async () => {
    render(<${component.name} />);

    const submitButton = screen.getByRole('button', { name: /submit|log in|sign in/i });

    // Mock a delayed API call
    vi.spyOn(global, 'fetch').mockImplementation(
      () => new Promise(resolve => setTimeout(resolve, 100))
    );

    fireEvent.click(submitButton);

    expect(submitButton).toBeDisabled();
    // or: expect(screen.getByText(/loading/i)).toBeInTheDocument();
  });

`;
    }
    generateErrorDisplayTest(component) {
        return `  it('displays API error messages', async () => {
    render(<${component.name} />);

    // Mock API error
    vi.spyOn(global, 'fetch').mockRejectedValueOnce({
      json: async () => ({ message: 'Invalid credentials' })
    });

    const submitButton = screen.getByRole('button', { name: /submit|log in|sign in/i });
    fireEvent.click(submitButton);

    await waitFor(() => {
      expect(screen.getByText(/invalid credentials|error/i)).toBeInTheDocument();
    });
  });

`;
    }
    generateSubmissionTest(component) {
        // Extract fields from component if available
        const fields = component.ui?.fields || [];
        let fillFields = '';
        for (const field of fields) {
            if (field.type === 'email') {
                fillFields += `    fireEvent.change(screen.getByLabelText(/${field.label}/i), { target: { value: 'test@example.com' } });\n`;
            }
            else if (field.type === 'password') {
                fillFields += `    fireEvent.change(screen.getByLabelText(/${field.label}/i), { target: { value: 'password123' } });\n`;
            }
            else if (field.type === 'text') {
                fillFields += `    fireEvent.change(screen.getByLabelText(/${field.label}/i), { target: { value: 'test value' } });\n`;
            }
        }
        return `  it('successfully submits the form', async () => {
    render(<${component.name} />);

${fillFields}
    const submitButton = screen.getByRole('button', { name: /submit|log in|sign in/i });
    fireEvent.click(submitButton);

    await waitFor(() => {
      // Verify submission behavior
      expect(submitButton).not.toBeDisabled();
    });
  });

`;
    }
    generateTestSetup(componentName, outputDir) {
        const content = `import { expect, afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import * as matchers from '@testing-library/jest-dom/matchers';

expect.extend(matchers);

afterEach(() => {
  cleanup();
});
`;
        return {
            path: path.join(outputDir, componentName, 'src', 'test', 'setup.ts'),
            content,
            overwrite: true,
        };
    }
    generateVitestConfig(componentName, outputDir) {
        const content = `import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/test/setup.ts'],
    exclude: ['**/e2e/**', '**/node_modules/**'],
    coverage: {
      reporter: ['text', 'json', 'html'],
      exclude: [
        'node_modules/',
        'src/test/',
      ],
    },
  },
});
`;
        return {
            path: path.join(outputDir, componentName, 'vitest.config.ts'),
            content,
            overwrite: false,
        };
    }
}
exports.FrontendTestGenerator = FrontendTestGenerator;
//# sourceMappingURL=frontend-test-generator.js.map