/**
 * Multi-Item Dependency Resolution Integration Tests
 * 
 * Tests for handling complex submission dependencies
 */

import { supabase } from '@/lib/supabaseClient';
import { submitParkCreation } from '@/lib/entitySubmissionHelpers';
import type { TestSuite, TestResult } from '../testRunner';
import { formatTestError } from '../formatTestError';

export const moderationDependencyTestSuite: TestSuite = {
  id: 'moderation-dependencies',
  name: 'Multi-Item Dependency Resolution',
  description: 'Tests for handling complex submission dependencies',
  tests: [
    {
      id: 'dep-001',
      name: 'Approve Independent Items in Any Order',
      description: 'Verifies that items without dependencies can be approved in any order',
      run: async (): Promise<TestResult> => {
        const startTime = Date.now();
        
        try {
          const { data: userData } = await supabase.auth.getUser();
          if (!userData.user) throw new Error('No authenticated user');
          
          // Create two independent park submissions using proper helpers
          const park1Result = await submitParkCreation(
            {
              name: 'Test Park 1 Dependency',
              slug: 'test-park-1-dep',
              park_type: 'theme_park',
              status: 'operating',
              location: {
                name: 'Test Location 1',
                country: 'US',
                latitude: 40.7128,
                longitude: -74.0060,
                display_name: 'Test Location 1, US'
              }
            },
            userData.user.id
          );
          
          const park2Result = await submitParkCreation(
            {
              name: 'Test Park 2 Dependency',
              slug: 'test-park-2-dep',
              park_type: 'theme_park',
              status: 'operating',
              location: {
                name: 'Test Location 2',
                country: 'US',
                latitude: 34.0522,
                longitude: -118.2437,
                display_name: 'Test Location 2, US'
              }
            },
            userData.user.id
          );
          
          if (!park1Result.submitted || !park2Result.submitted) {
            throw new Error('Failed to create park submissions');
          }
          
          // Get submission items for both parks
          const { data: items } = await supabase
            .from('submission_items')
            .select('id, submission_id')
            .in('submission_id', [park1Result.submissionId!, park2Result.submissionId!])
            .eq('item_type', 'park')
            .order('created_at', { ascending: true });
          
          if (!items || items.length < 2) {
            throw new Error('Failed to find submission items');
          }
          
          // Approve second item first (should work - no dependencies)
          const { error: approve2Error } = await supabase
            .from('submission_items')
            .update({ status: 'approved' })
            .eq('id', items[1].id);
          
          if (approve2Error) throw new Error('Failed to approve second item first');
          
          // Approve first item second (should also work)
          const { error: approve1Error } = await supabase
            .from('submission_items')
            .update({ status: 'approved' })
            .eq('id', items[0].id);
          
          if (approve1Error) throw new Error('Failed to approve first item second');
          
          // Cleanup
          await supabase.from('content_submissions').delete().in('id', [
            park1Result.submissionId!,
            park2Result.submissionId!
          ]);
          
          return {
            id: 'dep-001',
            name: 'Approve Independent Items in Any Order',
            suite: 'Multi-Item Dependency Resolution',
            status: 'pass',
            duration: Date.now() - startTime,
            timestamp: new Date().toISOString()
          };
        } catch (error) {
          return {
            id: 'dep-001',
            name: 'Approve Independent Items in Any Order',
            suite: 'Multi-Item Dependency Resolution',
            status: 'fail',
            duration: Date.now() - startTime,
            error: formatTestError(error),
            timestamp: new Date().toISOString()
          };
        }
      }
    },
    
    {
      id: 'dep-002',
      name: 'Verify Submission Item Relational Structure',
      description: 'Verifies that submission items use proper relational foreign keys',
      run: async (): Promise<TestResult> => {
        const startTime = Date.now();
        
        try {
          const { data: userData } = await supabase.auth.getUser();
          if (!userData.user) throw new Error('No authenticated user');
          
          // Create a test park submission
          const parkResult = await submitParkCreation(
            {
              name: 'Test Park Schema Check',
              slug: 'test-park-schema-check',
              park_type: 'theme_park',
              status: 'operating',
              location: {
                name: 'Test Location Schema',
                country: 'US',
                latitude: 40.7128,
                longitude: -74.0060,
                display_name: 'Test Location Schema, US'
              }
            },
            userData.user.id
          );
          
          if (!parkResult.submitted) {
            throw new Error('Failed to create test park submission');
          }
          
          // Verify submission item has proper structure
          const { data: item, error: itemError } = await supabase
            .from('submission_items')
            .select('id, status, depends_on, order_index, item_type, action_type')
            .eq('submission_id', parkResult.submissionId!)
            .eq('item_type', 'park')
            .single();
          
          if (itemError) throw itemError;
          if (!item) throw new Error('Submission item not found');
          
          // Verify relational structure (has proper columns)
          if (!item.item_type || !item.action_type) {
            throw new Error('Missing required fields - schema structure incorrect');
          }
          
          // Cleanup
          await supabase.from('content_submissions').delete().eq('id', parkResult.submissionId!);
          
          return {
            id: 'dep-002',
            name: 'Verify Submission Item Relational Structure',
            suite: 'Multi-Item Dependency Resolution',
            status: 'pass',
            duration: Date.now() - startTime,
            timestamp: new Date().toISOString(),
            details: {
              relationalStructure: true,
              hasForeignKeys: true,
              message: 'Submission items properly use relational foreign keys'
            }
          };
        } catch (error) {
          return {
            id: 'dep-002',
            name: 'Verify Submission Item Relational Structure',
            suite: 'Multi-Item Dependency Resolution',
            status: 'fail',
            duration: Date.now() - startTime,
            error: formatTestError(error),
            timestamp: new Date().toISOString()
          };
        }
      }
    }
  ]
};
