#!/usr/bin/env node
/**
 * Email Configuration Test Script
 * Run this to verify your SMTP settings are working correctly
 *
 * Usage: node test-email.js your-test-email@example.com
 */

require("dotenv").config();
const nodemailer = require("nodemailer");

const testEmail = process.argv[2];

if (!testEmail) {
  console.log("\n❌ Please provide a test email address:");
  console.log("   node test-email.js your-email@example.com\n");
  process.exit(1);
}

console.log("\n📧 Sky Art Shop - Email Configuration Test\n");
console.log("─".repeat(50));

// Check if SMTP is configured
if (
  !process.env.SMTP_HOST ||
  !process.env.SMTP_USER ||
  !process.env.SMTP_PASS
) {
  console.log("\n❌ SMTP not configured!\n");
  console.log("Please edit your .env file and add:");
  console.log("─".repeat(50));
  console.log("SMTP_HOST=smtp.gmail.com");
  console.log("SMTP_PORT=587");
  console.log("SMTP_SECURE=false");
  console.log("SMTP_USER=your-gmail@gmail.com");
  console.log("SMTP_PASS=your-16-char-app-password");
  console.log('SMTP_FROM="Sky Art Shop" <your-gmail@gmail.com>');
  console.log("─".repeat(50));
  console.log("\nSee: https://myaccount.google.com/apppasswords\n");
  process.exit(1);
}

console.log("✓ SMTP Host:", process.env.SMTP_HOST);
console.log("✓ SMTP Port:", process.env.SMTP_PORT);
console.log("✓ SMTP User:", process.env.SMTP_USER);
console.log("✓ SMTP Pass:", "*".repeat(process.env.SMTP_PASS.length));
console.log("✓ From:", process.env.SMTP_FROM || '"Sky Art Shop"');
console.log("─".repeat(50));

async function testEmailSend() {
  console.log("\n⏳ Creating email transporter...");

  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: parseInt(process.env.SMTP_PORT) || 587,
    secure: process.env.SMTP_SECURE === "true",
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });

  console.log("⏳ Verifying connection...");

  try {
    await transporter.verify();
    console.log("✓ SMTP connection verified!\n");
  } catch (error) {
    console.log("\n❌ Connection failed:", error.message);
    console.log("\nCommon issues:");
    console.log("  • Wrong email or password");
    console.log("  • App Password not set up correctly");
    console.log("  • 2-Factor Auth not enabled on Gmail");
    console.log("  • Less secure apps blocked (use App Password instead)\n");
    process.exit(1);
  }

  console.log("⏳ Sending test email to:", testEmail);

  const testCode = Math.floor(100000 + Math.random() * 900000);

  try {
    const info = await transporter.sendMail({
      from:
        process.env.SMTP_FROM || `"Sky Art Shop" <${process.env.SMTP_USER}>`,
      to: testEmail,
      subject: "🎨 Sky Art Shop - Email Test Successful!",
      html: `
        <div style="font-family: 'Segoe UI', Arial, sans-serif; max-width: 500px; margin: 0 auto; padding: 30px; background: linear-gradient(135deg, #FFEBEB 0%, #FFD0D0 100%); border-radius: 20px;">
          <div style="text-align: center; margin-bottom: 20px;">
            <h1 style="color: #202023; margin: 0;">🎉 Email Works!</h1>
          </div>
          
          <div style="background: white; border-radius: 16px; padding: 30px; text-align: center;">
            <p style="color: #202023; font-size: 16px; margin-bottom: 20px;">
              Your Sky Art Shop email configuration is working correctly!
            </p>
            
            <p style="color: #666; font-size: 14px; margin-bottom: 10px;">
              Here's a sample verification code:
            </p>
            
            <div style="background: linear-gradient(135deg, #FCB1D8 0%, #F6CCDE 100%); border-radius: 12px; padding: 20px; margin: 20px 0;">
              <span style="font-size: 32px; font-weight: bold; color: #202023; letter-spacing: 8px;">${testCode}</span>
            </div>
            
            <p style="color: #888; font-size: 12px; margin-top: 20px;">
              This is a test email from Sky Art Shop backend.
            </p>
          </div>
          
          <p style="text-align: center; color: #666; font-size: 12px; margin-top: 20px;">
            © ${new Date().getFullYear()} Sky Art Shop
          </p>
        </div>
      `,
    });

    console.log("\n" + "═".repeat(50));
    console.log("  ✅ EMAIL SENT SUCCESSFULLY!");
    console.log("═".repeat(50));
    console.log("\n📬 Check your inbox at:", testEmail);
    console.log("   (Also check spam/junk folder)\n");
    console.log("Message ID:", info.messageId);
    console.log("\n🎉 Your email configuration is working!\n");
  } catch (error) {
    console.log("\n❌ Failed to send email:", error.message);
    console.log("\nFull error:", error);
    process.exit(1);
  }
}

testEmailSend();
