import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
    stages: [
        { duration: '30s', target: 10 },
        { duration: '1m', target: 50 },
        { duration: '30s', target: 0 },
    ],
    thresholds: {
        http_req_duration: ['p(95)<500'],
        http_req_failed: ['rate<0.01'],
    },
};

const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';

export default function () {
    const responses = http.batch([
        ['GET', `${BASE_URL}/api/users/page?page=0&size=10`, null, { tags: { name: 'UsersList' } }],
        ['GET', `${BASE_URL}/api/roles/page?page=0&size=10`, null, { tags: { name: 'RolesList' } }],
    ]);

    check(responses[0], {
        'users status is 200': (r) => r.status === 200,
        'users response time < 500ms': (r) => r.timings.duration < 500,
    });

    check(responses[1], {
        'roles status is 200': (r) => r.status === 200,
        'roles response time < 500ms': (r) => r.timings.duration < 500,
    });

    const singleUserRes = http.get(`${BASE_URL}/api/users/1`);
    check(singleUserRes, {
        'single user status is 200 or 404': (r) => r.status === 200 || r.status === 404,
        'single user response time < 300ms': (r) => r.timings.duration < 300,
    });

    const healthRes = http.get(`${BASE_URL}/actuator/health`);
    check(healthRes, {
        'health check status is 200': (r) => r.status === 200,
        'health check response time < 100ms': (r) => r.timings.duration < 100,
    });

    sleep(1);
}

export function handleSummary(data) {
    return {
        'stdout': textSummary(data, { indent: ' ', enableColors: true }),
        'performance-report.json': JSON.stringify(data, null, 2),
    };
}

function textSummary(data, options) {
    const indent = options?.indent || '';
    const colors = options?.enableColors || false;
    
    let summary = `\n${indent}📊 Performance Test Summary\n`;
    summary += `${indent}============================\n\n`;
    
    summary += `${indent}⏱️  HTTP Metrics:\n`;
    summary += `${indent}  - Total Requests: ${data.metrics.http_reqs?.values?.count || 0}\n`;
    summary += `${indent}  - Request Duration (p95): ${data.metrics.http_req_duration?.values?.['p(95)']?.toFixed(2) || 0}ms\n`;
    summary += `${indent}  - Request Failed Rate: ${(data.metrics.http_req_failed?.values?.rate * 100)?.toFixed(2) || 0}%\n`;
    
    summary += `\n${indent}📈 Iterations:\n`;
    summary += `${indent}  - Total: ${data.metrics.iterations?.values?.count || 0}\n`;
    summary += `${indent}  - Rate: ${data.metrics.iterations?.values?.rate?.toFixed(2) || 0}/s\n`;
    
    summary += `\n${indent}⏰ Test Duration: ${data.state?.testRunDurationMs ? (data.state.testRunDurationMs / 1000).toFixed(2) : 0}s\n`;
    
    return summary;
}
