const fs = require('fs');

async function runTests() {
  const BASE_URL = 'http://localhost:5001/api/v1';
  let token = '';

  try {
    console.log('1. Testing Health Endpoint...');
    const health = await fetch(`${BASE_URL}/health`);
    const healthData = await health.json();
    console.log('Health:', healthData);
    if (!health.ok) throw new Error('Health check failed');

    console.log('\n2. Testing Registration...');
    const regRes = await fetch(`${BASE_URL}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: 'admin@tech4biz.com', password: 'securepassword', role: 'ADMIN' })
    });
    console.log('Registration Status (Admin):', regRes.status);
    if (!regRes.ok && regRes.status !== 400) throw new Error('Registration failed');

    const regPartnerRes = await fetch(`${BASE_URL}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: 'partner@tech4biz.com', password: 'securepassword', role: 'PARTNER_USER' })
    });
    console.log('Registration Status (Partner):', regPartnerRes.status);
    if (!regPartnerRes.ok && regPartnerRes.status !== 400) throw new Error('Partner Registration failed');

    console.log('\n3. Testing Login...');
    const loginRes = await fetch(`${BASE_URL}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: 'admin@tech4biz.com', password: 'securepassword' })
    });
    const loginData = await loginRes.json();
    console.log('Login Status:', loginRes.status);
    if (!loginRes.ok) throw new Error('Login failed');
    token = loginData.accessToken;
    console.log('Received Access Token: ', token.substring(0, 15) + '...');

    console.log('\n4. Testing Organization Creation...');
    const orgRes = await fetch(`${BASE_URL}/organizations`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ name: 'Tech4Biz Partners' })
    });
    const orgData = await orgRes.json();
    console.log('Organization Created:', orgData);
    if (!orgRes.ok) throw new Error('Org creation failed');

    console.log('\n5. Testing Legal Document Creation...');
    const legalRes = await fetch(`${BASE_URL}/legal/documents`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ type: 'NDA', version: '1.0', content: 'You must not disclose anything.' })
    });
    const legalData = await legalRes.json();
    console.log('Legal Document Created:', legalData);
    if (!legalRes.ok) throw new Error('Legal creation failed');

    console.log('\n6. Testing Asset Upload...');
    // Create a dummy file
    fs.writeFileSync('test-file.txt', 'This is a test file for upload.');
    const formData = new FormData();
    const fileBlob = new Blob([fs.readFileSync('test-file.txt')], { type: 'text/plain' });
    formData.append('file', fileBlob, 'test-file.txt');
    formData.append('title', 'My Secret Document');

    const uploadRes = await fetch(`${BASE_URL}/assets/upload`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: formData
    });
    const uploadData = await uploadRes.json();
    console.log('Asset Uploaded:', uploadData);
    if (!uploadRes.ok) throw new Error('Upload failed');
    fs.unlinkSync('test-file.txt');

    console.log('\n✅ ALL TESTS PASSED SUCCESSFULLY!');
  } catch (error) {
    console.error('\n❌ TEST FAILED:', error);
  }
}

runTests();
