import http from 'k6/http';
import { check, sleep } from 'k6';
import { randomString } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';

export const options = {
    vus: 20,
    duration: '30s',
    thresholds: {
        'http_req_duration': ['p(95)<500'], // 95% of requests must complete below 500ms
    },
};

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

export default function () {
    // 1. Initiate Upload
    const userID = '00000000-0000-0000-0000-000000000001'; // Mock User ID
    const initPayload = JSON.stringify({
        filename: `loadtest_${randomString(8)}.mp3`,
        total_size: 1024 * 1024 * 3, // 3MB
        total_chunks: 3,
    });

    const params = {
        headers: {
            'Content-Type': 'application/json',
            // Assuming dev/test environment with bypassed auth or mock token
            'Authorization': 'Bearer local-dev-token',
        },
    };

    const initRes = http.post(`${BASE_URL}/tracks/upload/init`, initPayload, params);

    const isInitSuccess = check(initRes, {
        'init status is 200': (r) => r.status === 200,
        'has upload_id': (r) => r.json('upload_id') !== undefined,
    });

    if (!isInitSuccess) {
        console.error(`Init failed: ${initRes.status} ${initRes.body}`);
        sleep(1);
        return;
    }

    const uploadID = initRes.json('upload_id');

    // 2. Upload Chunks (3 chunks)
    // We use a dummy file content. In K6, usually we send multipart/form-data.
    // For simplicity and speed in this specific check, we assume the server handles the multipart correctly.

    for (let i = 1; i <= 3; i++) {
        const chunkData = {
            file: http.file(randomString(1024 * 1024), `chunk_${i}.bin`), // 1MB dummy chunk
            chunk_number: i.toString(),
            total_chunks: '3',
        };

        const chunkRes = http.post(`${BASE_URL}/tracks/upload/${uploadID}`, chunkData, {
            headers: { 'Authorization': 'Bearer local-dev-token' } // Boundary is handled automatically
        });

        check(chunkRes, {
            [`chunk ${i} status is 200`]: (r) => r.status === 200,
        });

        sleep(0.1); // Small think time
    }

    // 3. Finish Upload
    const finishRes = http.post(`${BASE_URL}/tracks/upload/${uploadID}/finish`, null, params);

    check(finishRes, {
        'finish status is 200': (r) => r.status === 200,
        'has file_path': (r) => r.json('file_path') !== undefined,
    });
}
