import { PrismaClient as PrismaClientAuth } from '../node_modules/.prisma/client-auth';
import * as dotenv from 'dotenv';
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

// Load environment variables
dotenv.config({ path: '.env' });

async function grantDeletePermission() {
  try {
    console.log('Granting DELETE permission on inappropriate_photo_reports table...\n');

    // Extract username from DATABASE_URL_AUTH
    const dbUrl = process.env.DATABASE_URL_AUTH;
    if (!dbUrl) {
      console.error('❌ DATABASE_URL_AUTH not found in environment variables');
      return;
    }

    // Parse the connection string to get username
    const match = dbUrl.match(/postgresql:\/\/([^:]+):/);
    if (!match) {
      console.error('❌ Could not parse username from DATABASE_URL_AUTH');
      console.log('Please run this SQL command manually:');
      console.log('GRANT DELETE ON TABLE inappropriate_photo_reports TO your_username;');
      return;
    }

    const username = match[1];
    console.log(`Found database user: ${username}`);
    console.log('');

    // Try to grant permission using psql
    const sqlCommand = `GRANT DELETE ON TABLE inappropriate_photo_reports TO ${username};`;
    
    console.log('Attempting to grant DELETE permission...');
    console.log(`SQL: ${sqlCommand}\n`);

    try {
      // Try to run as current user first
      const { stdout, stderr } = await execAsync(
        `psql -d punimtag_auth -c "${sqlCommand}"`
      );
      
      if (stdout) console.log(stdout);
      if (stderr && !stderr.includes('WARNING')) console.error(stderr);
      
      console.log('✅ DELETE permission granted successfully!');
    } catch (error: any) {
      console.log('⚠️  Could not grant permission automatically (may need sudo)');
      console.log('\nPlease run this command manually as PostgreSQL superuser:');
      console.log(`\nsudo -u postgres psql -d punimtag_auth -c "GRANT DELETE ON TABLE inappropriate_photo_reports TO ${username};"`);
      console.log('\nOr connect to PostgreSQL and run:');
      console.log(`\\c punimtag_auth`);
      console.log(`GRANT DELETE ON TABLE inappropriate_photo_reports TO ${username};`);
    }
  } catch (error: any) {
    console.error('Error:', error.message);
  }
}

grantDeletePermission();

