#!/usr/bin/env tsx
/**
 * Grant read-only permissions to viewer_readonly user
 * This script requires PostgreSQL superuser credentials
 */

import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

const SQL_COMMANDS = `
GRANT CONNECT ON DATABASE punimtag TO viewer_readonly;
GRANT USAGE ON SCHEMA public TO viewer_readonly;
GRANT SELECT ON TABLE photos TO viewer_readonly;
GRANT SELECT ON TABLE people TO viewer_readonly;
GRANT SELECT ON TABLE faces TO viewer_readonly;
GRANT SELECT ON TABLE person_encodings TO viewer_readonly;
GRANT SELECT ON TABLE tags TO viewer_readonly;
GRANT SELECT ON TABLE phototaglinkage TO viewer_readonly;
GRANT SELECT ON TABLE photo_favorites TO viewer_readonly;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO viewer_readonly;
`;

async function grantPermissions() {
  console.log('🔐 Attempting to grant database permissions...\n');

  // Try different connection methods
  const methods = [
    // Method 1: Try with PGPASSWORD environment variable
    () => {
      if (process.env.PGPASSWORD) {
        console.log('Trying with PGPASSWORD environment variable...');
        try {
          const result = execSync(
            `psql -h localhost -U postgres -d punimtag -c "${SQL_COMMANDS.replace(/\n/g, ' ')}"`,
            { 
              env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD },
              stdio: 'inherit'
            }
          );
          return true;
        } catch (error) {
          return false;
        }
      }
      return false;
    },
    // Method 2: Try with sudo (if NOPASSWD is configured)
    () => {
      console.log('Trying with sudo...');
      try {
        execSync(
          `sudo -u postgres psql -d punimtag -c "${SQL_COMMANDS.replace(/\n/g, ' ')}"`,
          { stdio: 'inherit' }
        );
        return true;
      } catch (error) {
        return false;
      }
    },
  ];

  for (const method of methods) {
    try {
      if (method()) {
        console.log('\n✅ Permissions granted successfully!');
        return;
      }
    } catch (error) {
      // Continue to next method
    }
  }

  // If all methods fail, provide manual instructions
  console.log('\n❌ Could not automatically grant permissions.\n');
  console.log('Please run the SQL commands manually as PostgreSQL superuser:\n');
  console.log('Option 1: Using psql with password:');
  console.log('  PGPASSWORD=your_password psql -U postgres -d punimtag');
  console.log('  Then paste these commands:');
  console.log(SQL_COMMANDS);
  console.log('\nOption 2: Using sudo:');
  console.log('  sudo -u postgres psql -d punimtag');
  console.log('  Then paste these commands:');
  console.log(SQL_COMMANDS);
  console.log('\nOption 3: Run the SQL file:');
  console.log('  psql -U postgres -d punimtag -f grant_permissions_now.sql');
  
  process.exit(1);
}

grantPermissions().catch((error) => {
  console.error('Error:', error);
  process.exit(1);
});








