
import axios from 'axios';
import FormData from 'form-data';
import fs from 'fs';
import path from 'path';

const API_URL = 'http://localhost:9899/api';

async function testUpload() {
    try {
        // 1. Create a dummy file
        const filePath = path.join(__dirname, 'test-image.png');
        if (!fs.existsSync(filePath)) {
            // Create a 1x1 transparent png for testing if not exists
            const buffer = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64');
            fs.writeFileSync(filePath, buffer);
        }

        console.log('Testing upload with file:', filePath);

        // 2. Register/Login to get a user ID (or create a dummy user directly if possible, but let's assume we need a user id)
        // For simplicity, let's create a dummy user in DB manually or use a known ID if we had one.
        // Actually, let's try to register a temp user.
        const uniqueEmail = `test${Date.now()}@example.com`;
        console.log('Registering temp user:', uniqueEmail);

        let userId;
        let token;

        try {
            const regRes = await axios.post(`${API_URL}/auth/register`, {
                firstName: 'Test',
                lastName: 'User',
                email: uniqueEmail,
                userType: 'doctor'
            });
            userId = regRes.data.user.id;
            console.log('User registered with ID:', userId);
        } catch (e: any) {
            console.error('Registration failed:', e.response?.data || e.message);
            return;
        }

        // 3. Upload Profile Image
        const formData = new FormData();
        formData.append('profileImage', fs.createReadStream(filePath));
        formData.append('userId', userId);

        console.log('Uploading profile image...');
        const uploadRes = await axios.post(`${API_URL}/upload/profile-image`, formData, {
            headers: {
                ...formData.getHeaders()
            }
        });

        if (uploadRes.data.success) {
            const filePath = uploadRes.data.filePath;
            const displayPath = filePath.length > 50 ? filePath.substring(0, 50) + '...' : filePath;
            console.log('✓ Profile image upload successful (Base64 length):', filePath.length);
            console.log('  Preview:', displayPath);
        } else {
            console.error('❌ Profile image upload failed:', uploadRes.data);
        }

        // 4. Upload Signature
        const sigFormData = new FormData();
        sigFormData.append('signature', fs.createReadStream(filePath));
        sigFormData.append('userId', userId);

        console.log('Uploading signature...');
        // We need a doctor profile for this. The register endpoint creates a User, checks if it creates a Doctor model? 
        // The previous code showed Doctor model requires userId. 
        // AuthController.register creates a User. It doesn't seem to create a Doctor document automatically in the snippet I saw.
        // So this might fail if the Doctor document doesn't exist.
        // Let's check if we need to create a doctor profile first.
        // Depending on logic, maybe I should create it manually here or ensure my test covers it.
        // For now I'll try to upload, if it fails due to "Doctor not found", I know why.
        // Actually, let's just create a doctor record via mongoose directly if we could, 
        // OR just rely on the fact that maybe the app creates it later?
        // Let's assume for now we might need to manually ensure doctor exists or if the upload controller handles it (it does `Doctor.findOne`).
        // So if no doctor doc, it fails.
        // I'll skip signature test if I can't easily create a doctor, OR I can try to create one via API if there is one.
        // Checking DoctorController... I didn't see it but `AuthController` calls `User`.

        try {
            const sigRes = await axios.post(`${API_URL}/upload/signature`, sigFormData, {
                headers: {
                    ...sigFormData.getHeaders()
                }
            });
            if (sigRes.data.success) {
                const filePath = sigRes.data.filePath;
                const displayPath = filePath.length > 50 ? filePath.substring(0, 50) + '...' : filePath;
                console.log('✓ Signature upload successful (Base64 length):', filePath.length);
                console.log('  Preview:', displayPath);
            }
        } catch (e: any) {
            console.log('Note: Signature upload might have failed if Doctor profile not created:', e.response?.data?.error);
        }

        // Cleanup
        fs.unlinkSync(filePath);

    } catch (error: any) {
        console.error('Test failed:', error.message);
        if (error.response) {
            console.error('Response data:', error.response.data);
        }
    }
}

testUpload();
