/**
 * Seed Script: Save Google OAuth credentials to YouTubeAppConfig
 *
 * This script programmatically saves the platform-wide Google OAuth credentials
 * to the YouTubeAppConfig MongoDB collection — the same mechanism used by
 * Super Admin → Settings → YouTube API configuration in the UI.
 *
 * After running this script, both YouTube and Google Drive integrations will
 * detect the configured OAuth credentials and stop showing "not configured" errors.
 *
 * Usage: npx tsx scripts/seed-google-oauth.ts
 *
 * Optional environment variables (override defaults):
 *   GOOGLE_CLIENT_ID       — Google OAuth Client ID
 *   GOOGLE_CLIENT_SECRET   — Google OAuth Client Secret
 *   GOOGLE_REDIRECT_URL     — YouTube OAuth redirect URL
 */

import mongoose from 'mongoose';
import * as dotenv from 'dotenv';
import * as path from 'path';
import crypto from 'crypto';

// Load env from backend .env
dotenv.config({ path: path.join(__dirname, '../.env') });

// ============================================
// CONFIGURATION
// ============================================

const CLIENT_ID = process.env.GOOGLE_CLIENT_ID || '583284418380-9kpgpdeik2ndcppk8dedhbtc4grdhjda.apps.googleusercontent.com';
const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET || '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';
const REDIRECT_URL = process.env.GOOGLE_REDIRECT_URL || process.env.YOUTUBE_REDIRECT_URL || 'http://localhost:3101/api/youtube/auth/callback';

const PLATFORM_CONFIG_KEY = 'platform';

// ============================================
// ENCRYPTION (same as src/services/utils/encryption.ts)
// ============================================

const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;

// Must match the app's ENCRYPTION_KEY — uses the same fallback as the running app
const DEV_ENCRYPTION_KEY = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2';

function getEncryptionKey(): Buffer {
  const key = process.env.ENCRYPTION_KEY;
  if (!key) {
    console.warn('⚠️  ENCRYPTION_KEY not set — using dev key. Make sure the app uses the same key.');
    return Buffer.from(DEV_ENCRYPTION_KEY, 'hex');
  }
  if (!/^[0-9a-fA-F]{64}$/.test(key)) {
    console.error('❌ ENCRYPTION_KEY must be exactly 64 hex characters. Got:', key.length, 'chars');
    process.exit(1);
  }
  return Buffer.from(key, 'hex');
}

function encryptApiKey(plaintext: string): { encrypted: string; iv: string } {
  const key = getEncryptionKey();
  const iv = crypto.randomBytes(IV_LENGTH);
  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);

  let encrypted = cipher.update(plaintext, 'utf8', 'hex');
  encrypted += cipher.final('hex');

  const authTag = cipher.getAuthTag();

  // Format: "ciphertext:authTag" — matches the app's encryptApiKey()
  return {
    encrypted: `${encrypted}:${authTag.toString('hex')}`,
    iv: iv.toString('hex'),
  };
}

// ============================================
// MONGOOSE SCHEMA (minimal, matches YouTubeAppConfig)
// ============================================

const YouTubeAppConfigSchema = new mongoose.Schema({
  companyId: {
    type: String,
    required: true,
    index: true,
  },
  encryptedClientId: {
    type: String,
    select: false,
  },
  clientIdIV: {
    type: String,
    select: false,
  },
  encryptedClientSecret: {
    type: String,
    select: false,
  },
  clientSecretIV: {
    type: String,
    select: false,
  },
  redirectUrl: {
    type: String,
    default: '',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
  collection: 'youtubeappconfigs',
});

YouTubeAppConfigSchema.index({ companyId: 1 }, { unique: true });

// ============================================
// MAIN
// ============================================

async function main() {
  const MONGODB_URI = process.env.MONGODB_URI;
  if (!MONGODB_URI) {
    console.error('❌ MONGODB_URI not set in .env');
    process.exit(1);
  }

  console.log('🔌 Connecting to MongoDB...');
  await mongoose.connect(MONGODB_URI);
  console.log('✅ Connected to MongoDB');

  const YouTubeAppConfig = mongoose.model('YouTubeAppConfig', YouTubeAppConfigSchema);

  // Validate inputs
  if (!CLIENT_ID.endsWith('.apps.googleusercontent.com')) {
    console.error('❌ Invalid Client ID — must end with .apps.googleusercontent.com');
    console.error('   Got:', CLIENT_ID);
    process.exit(1);
  }

  if (!CLIENT_SECRET) {
    console.error('❌ Client Secret is required');
    process.exit(1);
  }

  try {
    new URL(REDIRECT_URL);
  } catch {
    console.error('❌ Invalid redirect URL:', REDIRECT_URL);
    process.exit(1);
  }

  // Encrypt credentials using the same method as the app
  console.log('🔐 Encrypting credentials...');
  const encryptedId = encryptApiKey(CLIENT_ID);
  const encryptedSecret = encryptApiKey(CLIENT_SECRET);

  // Upsert the platform singleton (same approach as saveYouTubeCredentials)
  console.log('💾 Saving YouTubeAppConfig with companyId = "platform"...');
  await YouTubeAppConfig.deleteMany({});
  const doc = await YouTubeAppConfig.create({
    companyId: PLATFORM_CONFIG_KEY,
    encryptedClientId: encryptedId.encrypted,
    clientIdIV: encryptedId.iv,
    encryptedClientSecret: encryptedSecret.encrypted,
    clientSecretIV: encryptedSecret.iv,
    redirectUrl: REDIRECT_URL,
    updatedBy: 'seed-script',
  });

  console.log('✅ Google OAuth credentials saved successfully!');
  console.log('');
  console.log('📋 Saved configuration:');
  console.log(`   Client ID:      ${CLIENT_ID.slice(0, 12)}…${CLIENT_ID.slice(-25)}`);
  console.log(`   Client Secret:  ${CLIENT_SECRET.slice(0, 6)}…`);
  console.log(`   Redirect URL:   ${REDIRECT_URL}`);
  console.log(`   Document ID:    ${doc._id}`);
  console.log('');
  console.log('🎯 Both YouTube (Social Media OS) and Google Drive (Backup & Restore)');
  console.log('   integrations will now detect these credentials via getYouTubeCredentials().');
  console.log('');
  console.log('⚠️  REMINDER: Make sure you have also:');
  console.log('   1. Added http://localhost:3101/api/google-drive/auth/callback to your');
  console.log('      Google Cloud Console → OAuth client → Authorized redirect URIs');
  console.log('   2. Enabled the Google Drive API in Google Cloud Console');
  console.log('   3. Enabled the YouTube Data API v3 in Google Cloud Console (if not already)');

  await mongoose.disconnect();
  console.log('');
  console.log('👋 Done. MongoDB disconnected.');
}

main().catch((err) => {
  console.error('❌ Failed to seed Google OAuth credentials:', err);
  process.exit(1);
});