import { UserRole } from "@/lib/auth/roles";

export interface InvitationEmailData {
  to: string;
  inviteToken: string;
  invitedBy: string;
  role: UserRole;
  siteIds?: string[];
  message?: string;
}

const ROLE_NAMES: Record<UserRole, string> = {
  [UserRole.SUPER_ADMIN]: "슈퍼 관리자",
  [UserRole.SITE_ADMIN]: "사이트 관리자",
  [UserRole.EDITOR]: "편집자",
  [UserRole.VIEWER]: "뷰어",
};

export async function sendInvitationEmail(
  data: InvitationEmailData
): Promise<void> {
  const { to, inviteToken, invitedBy, role, siteIds, message } = data;

  // Create invitation URL
  const baseUrl = process.env.NEXTAUTH_URL || "http://localhost:3000";
  const inviteUrl = `${baseUrl}/auth/accept-invite?token=${encodeURIComponent(
    inviteToken
  )}`;

  // Prepare email content
  const roleName = ROLE_NAMES[role];
  const siteInfo =
    siteIds && siteIds.length > 0
      ? `\n\n할당된 사이트: ${siteIds.join(", ")}`
      : "";

  const emailContent = `
안녕하세요,

${invitedBy}님이 AgentC 다중 사이트 관리 시스템에 초대하셨습니다.

초대 정보:
- 역할: ${roleName}${siteInfo}

${message ? `\n메시지:\n${message}\n` : ""}

아래 링크를 클릭하여 계정을 활성화하세요:
${inviteUrl}

이 초대는 7일 후에 만료됩니다.

감사합니다.
AgentC 팀
  `.trim();

  // In a real implementation, this would use a proper email service
  // For now, we'll log the email content and simulate sending
  console.log("=== 초대 이메일 발송 ===");
  console.log(`받는 사람: ${to}`);
  console.log(`제목: AgentC 시스템 초대`);
  console.log(`내용:\n${emailContent}`);
  console.log("========================");

  // Simulate email sending delay
  await new Promise((resolve) => setTimeout(resolve, 100));

  // In production, you would integrate with services like:
  // - SendGrid
  // - AWS SES
  // - Nodemailer with SMTP
  // - Resend
  // etc.

  /*
  Example with Nodemailer:
  
  import nodemailer from 'nodemailer';
  
  const transporter = nodemailer.createTransporter({
    host: process.env.EMAIL_SERVER_HOST,
    port: parseInt(process.env.EMAIL_SERVER_PORT || '587'),
    secure: false,
    auth: {
      user: process.env.EMAIL_SERVER_USER,
      pass: process.env.EMAIL_SERVER_PASSWORD,
    },
  });

  await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to,
    subject: 'AgentC 시스템 초대',
    text: emailContent,
    html: `<pre>${emailContent}</pre>`,
  });
  */
}

export async function sendWelcomeEmail(
  email: string,
  name: string
): Promise<void> {
  const welcomeContent = `
안녕하세요 ${name}님,

AgentC 다중 사이트 관리 시스템에 오신 것을 환영합니다!

계정이 성공적으로 활성화되었습니다. 이제 시스템에 로그인하여 할당된 사이트를 관리할 수 있습니다.

로그인 페이지: ${process.env.NEXTAUTH_URL}/admin/login

궁금한 점이 있으시면 언제든지 문의해 주세요.

감사합니다.
AgentC 팀
  `.trim();

  console.log("=== 환영 이메일 발송 ===");
  console.log(`받는 사람: ${email}`);
  console.log(`제목: AgentC 시스템 가입을 환영합니다`);
  console.log(`내용:\n${welcomeContent}`);
  console.log("========================");

  await new Promise((resolve) => setTimeout(resolve, 100));
}
