// tests/api/06-edge-cases.ts
// Validation and Error Handling Tests

import { join } from 'path';
import { api, log, runTest, testContext, uploadFile, exitWithTestResults } from './utils';
import { config, endpoints } from './config';

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

async function main() {
  log.section('EDGE CASES & VALIDATION TESTS');

  // Test 1: Invalid alias format
  await runTest('Invalid alias format', async () => {
    const invalidAliases = ['no-at-symbol', '@has spaces', '@special!chars', ''];

    for (const invalid of invalidAliases) {
      try {
        const result = await api(endpoints.generations, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            prompt: 'Test',
            aspectRatio: '1:1',
            alias: invalid,
          }),
          expectError: true,
        });

        if (result.status >= 400) {
          log.detail(`"${invalid}" correctly rejected`, '✓');
        } else {
          log.warning(`"${invalid}" was accepted!`);
        }
      } catch (error) {
        log.detail(`"${invalid}" correctly rejected`, '✓');
      }
    }
  });

  // Test 2: Invalid aspect ratio
  await runTest('Invalid aspect ratio', async () => {
    try {
      const result = await api(endpoints.generations, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          prompt: 'Test',
          aspectRatio: 'invalid',
        }),
        expectError: true,
      });

      if (result.status >= 400) {
        log.detail('Invalid aspect ratio rejected', '✓');
      }
    } catch (error) {
      log.detail('Invalid aspect ratio rejected', '✓');
    }
  });

  // Test 3: Missing required fields
  await runTest('Missing required fields', async () => {
    try {
      const result = await api(endpoints.generations, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          // Missing prompt
          aspectRatio: '1:1',
        }),
        expectError: true,
      });

      if (result.status >= 400) {
        log.detail('Missing prompt rejected', '✓');
      }
    } catch (error) {
      log.detail('Missing prompt rejected', '✓');
    }
  });

  // Test 4: Non-existent resources
  await runTest('404 for non-existent resources', async () => {
    const fakeUuid = '00000000-0000-0000-0000-000000000000';

    const tests = [
      { url: `${endpoints.images}/${fakeUuid}`, name: 'image' },
      { url: `${endpoints.generations}/${fakeUuid}`, name: 'generation' },
      { url: `${endpoints.flows}/${fakeUuid}`, name: 'flow' },
    ];

    for (const test of tests) {
      try {
        const result = await api(test.url, { expectError: true });
        if (result.status === 404) {
          log.detail(`${test.name} 404`, '✓');
        }
      } catch (error) {
        log.detail(`${test.name} 404`, '✓');
      }
    }
  });

  // Test 5: Regenerate successful generation
  await runTest('Regenerate successful generation', async () => {
    // Create a generation first
    const result = await api(endpoints.generations, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt: 'Test for regenerate',
        aspectRatio: '1:1',
      }),
    });

    // Wait briefly (not full completion)
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Regenerate
    const regen = await api(`${endpoints.generations}/${result.data.data.id}/regenerate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({}),
    });

    if (!regen.data.data) {
      throw new Error('No regeneration returned');
    }

    log.detail('Regenerate triggered', '✓');
  });

  // Test 6: CDN image by filename (if implemented)
  await runTest('CDN endpoints exist', async () => {
    // Just verify the endpoint structure exists
    log.detail('CDN endpoints', 'not fully tested (no org/project context)');
  });

  log.section('EDGE CASES & VALIDATION TESTS COMPLETED');
}

main()
  .then(() => exitWithTestResults())
  .catch((error) => {
    console.error('Unexpected error:', error);
    process.exit(1);
  });
