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

import { supabase } from '@/integrations/supabase/client';
import type { TestSuite, TestResult } from '../testRunner';

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 submission with 2 independent park items
          const { data: submission, error: createError } = await supabase
            .from('content_submissions')
            .insert({
              user_id: userData.user.id,
              submission_type: 'park',
              status: 'pending',
              content: { test: true }
            })
            .select()
            .single();
          
          if (createError) throw createError;
          
          // Create two park submission items (independent)
          const { error: items1Error } = await supabase
            .from('submission_items')
            .insert([
              {
                submission_id: submission.id,
                item_type: 'park',
                item_data: { name: 'Test Park 1', slug: 'test-park-1', country: 'US' },
                status: 'pending'
              },
              {
                submission_id: submission.id,
                item_type: 'park',
                item_data: { name: 'Test Park 2', slug: 'test-park-2', country: 'US' },
                status: 'pending'
              }
            ]);
          
          if (items1Error) throw items1Error;
          
          // Get items
          const { data: items } = await supabase
            .from('submission_items')
            .select('id')
            .eq('submission_id', submission.id)
            .order('created_at', { ascending: true });
          
          if (!items || items.length !== 2) {
            throw new Error('Failed to create 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().eq('id', submission.id);
          
          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: error instanceof Error ? error.message : String(error),
            timestamp: new Date().toISOString()
          };
        }
      }
    },
    
    {
      id: 'dep-002',
      name: 'Verify Submission Item Dependencies Exist',
      description: 'Verifies that submission items have proper dependency tracking',
      run: async (): Promise<TestResult> => {
        const startTime = Date.now();
        
        try {
          // Verify submission_items table has dependency columns
          const { data: testItem } = await supabase
            .from('submission_items')
            .select('id, status')
            .limit(1)
            .maybeSingle();
          
          // If query succeeds, table exists and is accessible
          return {
            id: 'dep-002',
            name: 'Verify Submission Item Dependencies Exist',
            suite: 'Multi-Item Dependency Resolution',
            status: 'pass',
            duration: Date.now() - startTime,
            timestamp: new Date().toISOString(),
            details: {
              tableAccessible: true,
              testQuery: 'submission_items table verified'
            }
          };
        } catch (error) {
          return {
            id: 'dep-002',
            name: 'Verify Submission Item Dependencies Exist',
            suite: 'Multi-Item Dependency Resolution',
            status: 'fail',
            duration: Date.now() - startTime,
            error: error instanceof Error ? error.message : String(error),
            timestamp: new Date().toISOString()
          };
        }
      }
    }
  ]
};
