import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { sendEmail } from '@/lib/email';
import { logger } from '@/lib/logger';

const bodySchema = z.object({
  to: z.string().email().optional(),
});

/**
 * Fire a test email through the per-port sales SMTP credentials. Used by
 * the admin "Test SMTP" button on the Sales email config card to verify
 * connectivity / auth without waiting for the next real send to fail.
 *
 * Sends a small text/HTML message to either the body-supplied `to` or
 * (default) the admin's own email so they get the verification in their
 * inbox. Returns { ok: true } on success or { ok: false, error } on
 * failure - the admin UI rates accordingly.
 */
export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const body = await parseBody(req, bodySchema);
      const recipient = body.to ?? ctx.user.email;
      if (!recipient) {
        return NextResponse.json(
          { data: { ok: false, error: 'No recipient resolved - sign-in email is empty' } },
          { status: 200 },
        );
      }

      try {
        const subject = `Port Nimara CRM - SMTP test (${new Date().toLocaleTimeString()})`;
        const html = `<p>Hello,</p><p>This is a test message sent from your CRM's <strong>Sales SMTP</strong> configuration. If you received this, your SMTP credentials work.</p><p style="color:#666;font-size:12px;">Timestamp: ${new Date().toISOString()}</p>`;
        const text = `This is a test message sent from your CRM's Sales SMTP configuration. If you received this, your SMTP credentials work.\n\nTimestamp: ${new Date().toISOString()}`;
        await sendEmail(recipient, subject, html, undefined, text, ctx.portId);
        return NextResponse.json({ data: { ok: true, to: recipient } });
      } catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        logger.warn({ portId: ctx.portId, err: message }, 'Sales SMTP test send failed');
        return NextResponse.json({ data: { ok: false, error: message } });
      }
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
