import { QueryInterface } from 'sequelize';

/**
 * Add foreign key constraint for template_id after workflow_templates table exists
 * This should run after both:
 * - 20251210-enhance-workflow-templates (creates workflow_templates table)
 * - 20251210-add-workflow-type-support (adds template_id column)
 */
export async function up(queryInterface: QueryInterface): Promise<void> {
  // Check if workflow_templates table exists
  const [tables] = await queryInterface.sequelize.query(`
    SELECT table_name 
    FROM information_schema.tables 
    WHERE table_schema = 'public' 
    AND table_name = 'workflow_templates';
  `);

  if (tables.length > 0) {
    // Check if foreign key already exists
    const [constraints] = await queryInterface.sequelize.query(`
      SELECT constraint_name
      FROM information_schema.table_constraints
      WHERE table_schema = 'public'
      AND table_name = 'workflow_requests'
      AND constraint_name = 'workflow_requests_template_id_fkey';
    `);

    if (constraints.length === 0) {
      // Add foreign key constraint
      await queryInterface.sequelize.query(`
        ALTER TABLE workflow_requests
        ADD CONSTRAINT workflow_requests_template_id_fkey
        FOREIGN KEY (template_id)
        REFERENCES workflow_templates(template_id)
        ON UPDATE CASCADE
        ON DELETE SET NULL;
      `);
    }
  }
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  // Remove foreign key constraint if it exists
  try {
    await queryInterface.sequelize.query(`
      ALTER TABLE workflow_requests
      DROP CONSTRAINT IF EXISTS workflow_requests_template_id_fkey;
    `);
  } catch (error) {
    // Ignore if constraint doesn't exist
    console.log('Note: Foreign key constraint may not exist');
  }
}

