// tests/api/05-live.ts
// Live URLs and Scope Management Tests

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

async function main() {
  log.section('LIVE URL & SCOPE TESTS');

  // Test 1: Create scope manually
  await runTest('Create live scope', async () => {
    const result = await api(`${endpoints.live}/scopes`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        slug: 'test-scope',
        allowNewGenerations: true,
        newGenerationsLimit: 50,
      }),
    });

    if (!result.data.data) {
      throw new Error('No scope returned');
    }

    log.detail('Scope slug', result.data.data.slug);
    log.detail('Allow new generations', result.data.data.allowNewGenerations);
    log.detail('Limit', result.data.data.newGenerationsLimit);
  });

  // Test 2: List scopes
  await runTest('List all scopes', async () => {
    const result = await api(`${endpoints.live}/scopes`);

    if (!result.data.data || !Array.isArray(result.data.data)) {
      throw new Error('No scopes array returned');
    }

    log.detail('Total scopes', result.data.data.length);
  });

  // Test 3: Get scope details
  await runTest('Get scope details', async () => {
    const result = await api(`${endpoints.live}/scopes/test-scope`);

    if (!result.data.data) {
      throw new Error('Scope not found');
    }

    const scope = result.data.data;
    if (typeof scope.currentGenerations !== 'number') {
      throw new Error('Missing currentGenerations count');
    }

    log.detail('Slug', scope.slug);
    log.detail('Current generations', scope.currentGenerations);
  });

  // Test 4: Update scope settings
  await runTest('Update scope settings', async () => {
    const result = await api(`${endpoints.live}/scopes/test-scope`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        allowNewGenerations: false,
        newGenerationsLimit: 100,
      }),
    });

    if (!result.data.data) {
      throw new Error('No scope returned');
    }

    const scope = result.data.data;
    if (scope.allowNewGenerations !== false) {
      throw new Error('Setting not updated');
    }

    log.detail('Allow new generations', scope.allowNewGenerations);
    log.detail('New limit', scope.newGenerationsLimit);
  });

  // Test 5: Live URL - basic generation
  await runTest('Live URL - basic generation', async () => {
    // Re-enable generation for testing
    await api(`${endpoints.live}/scopes/test-scope`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        allowNewGenerations: true,
      }),
    });

    // Live endpoint requires prompt query parameter
    const testPrompt = encodeURIComponent('A simple blue square on white background');
    const result = await api(`${endpoints.live}?prompt=${testPrompt}`, {
      method: 'GET',
    });

    // Response should be image bytes or generation info
    log.detail('Response received', '✓');
    log.detail('Status', result.status);
  });

  // Test 6: Scope regenerate
  await runTest('Regenerate scope images', async () => {
    const result = await api(`${endpoints.live}/scopes/test-scope/regenerate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({}),
    });

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

  // Test 7: Delete scope
  await runTest('Delete scope', async () => {
    await api(`${endpoints.live}/scopes/test-scope`, {
      method: 'DELETE',
    });

    // Verify deleted - check for 404 status
    const result = await api(`${endpoints.live}/scopes/test-scope`, {
      expectError: true,
    });

    if (result.status !== 404) {
      throw new Error('Scope should be deleted');
    }
    log.detail('Scope deleted', '✓');
  });

  log.section('LIVE URL & SCOPE TESTS COMPLETED');
}

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