import { NextRequest, NextResponse } from 'next/server';
import { requireAdmin } from '@/lib/admin-auth';
import { getRequestBaseUrl, isValidEmail, normalizeEmail, sendTemplatedEmail } from '@/lib/email-service';
import { getDbClient } from '@/storage/database/local-db';

export const runtime = 'nodejs';

const MAX_TARGETED_RECIPIENTS = 200;
const MAX_BROADCAST_RECIPIENTS = 5000;
type AdminMailKind = 'notification' | 'admin';

function normalizeMailKind(value: unknown): AdminMailKind {
  return value === 'admin' ? 'admin' : 'notification';
}

function normalizeIdList(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return [...new Set(value
    .filter((item): item is string => typeof item === 'string')
    .map(item => item.trim())
    .filter(item => /^[0-9a-fA-F-]{36}$/.test(item)))];
}

function normalizeEmailList(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return [...new Set(value
    .map(normalizeEmail)
    .filter(isValidEmail))];
}

async function loadRecipients(client: Awaited<ReturnType<typeof getDbClient>>, body: Record<string, unknown>) {
  const mode = body.mode === 'all' ? 'all' : 'selected';

  if (mode === 'all') {
    const result = await client.query(
      `SELECT id, email
       FROM profiles
       WHERE COALESCE(role, 'user') NOT IN ('admin', 'enterprise_admin')
         AND COALESCE(is_active, true) = true
         AND COALESCE(email, '') <> ''
       ORDER BY created_at ASC
       LIMIT $1`,
      [MAX_BROADCAST_RECIPIENTS],
    );
    return result.rows
      .map(row => ({ id: String(row.id), email: normalizeEmail(row.email) }))
      .filter(row => isValidEmail(row.email));
  }

  const userIds = normalizeIdList(body.userIds);
  const emails = normalizeEmailList(body.emails);

  if (userIds.length === 0 && emails.length === 0) return [];
  if (userIds.length + emails.length > MAX_TARGETED_RECIPIENTS) {
    throw new Error(`单次指定发送最多 ${MAX_TARGETED_RECIPIENTS} 个收件人`);
  }

  const result = await client.query(
    `SELECT id, email
     FROM profiles
     WHERE COALESCE(role, 'user') NOT IN ('admin', 'enterprise_admin')
       AND COALESCE(is_active, true) = true
       AND COALESCE(email, '') <> ''
       AND (
         id = ANY($1::uuid[])
         OR LOWER(email) = ANY($2::text[])
       )`,
    [userIds, emails],
  );

  return result.rows
    .map(row => ({ id: String(row.id), email: normalizeEmail(row.email) }))
    .filter(row => isValidEmail(row.email));
}

export async function POST(request: NextRequest) {
  const adminError = await requireAdmin(request);
  if (adminError) return adminError;

  const client = await getDbClient();
  try {
    const body = await request.json().catch(() => ({})) as Record<string, unknown>;
    const title = typeof body.title === 'string' ? body.title.trim().slice(0, 120) : '';
    const content = typeof body.content === 'string' ? body.content.trim().slice(0, 5000) : '';
    const buttonText = typeof body.buttonText === 'string' ? body.buttonText.trim().slice(0, 40) : '';
    const buttonUrl = typeof body.buttonUrl === 'string' ? body.buttonUrl.trim().slice(0, 500) : '';
    const mailKind = normalizeMailKind(body.mailKind);
    const mailKindLabel = mailKind === 'admin' ? '管理员邮件' : '通知邮件';

    if (!title || !content) {
      return NextResponse.json({ error: '请填写邮件标题和正文内容' }, { status: 400 });
    }
    if (buttonUrl && !/^https?:\/\/[^\s"'<>]+$/i.test(buttonUrl)) {
      return NextResponse.json({ error: '按钮链接必须是 HTTP(S) 地址' }, { status: 400 });
    }

    const recipients = await loadRecipients(client, body);
    const uniqueRecipients = [...new Map(recipients.map(item => [item.email, item])).values()];
    if (uniqueRecipients.length === 0) {
      return NextResponse.json({ error: '没有可发送的非管理员用户邮箱' }, { status: 400 });
    }

    let sent = 0;
    const failed: Array<{ email: string; error: string }> = [];
    const assetBaseUrl = getRequestBaseUrl(request) || undefined;

    for (const recipient of uniqueRecipients) {
      try {
        await sendTemplatedEmail(client, {
          to: recipient.email,
          type: mailKind === 'admin' ? 'business' : 'announcement',
          subject: `【妙境】${title}`,
          title,
          body: content,
          buttonText: buttonText || undefined,
          buttonUrl: buttonUrl || undefined,
          note: `这是一封${mailKindLabel}，请勿直接回复。`,
          templateKind: mailKind,
          ipAddress: body.mode === 'all' ? 'admin-broadcast' : 'admin-targeted',
          assetBaseUrl,
        });
        sent += 1;
      } catch (error) {
        failed.push({
          email: recipient.email,
          error: error instanceof Error ? error.message : String(error),
        });
      }
    }

    return NextResponse.json({
      success: failed.length === 0,
      total: uniqueRecipients.length,
      sent,
      failedCount: failed.length,
      failed: failed.slice(0, 20),
      message: failed.length === 0
        ? `邮件已发送给 ${sent} 个用户`
        : `已发送 ${sent} 封，失败 ${failed.length} 封`,
    }, { status: sent > 0 ? 200 : 400 });
  } catch (error) {
    const message = error instanceof Error ? error.message : '邮件发送失败';
    return NextResponse.json({ error: message }, { status: 400 });
  } finally {
    client.release();
  }
}
