import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { adapters } from '@root/adapters.config';
import { getWorkspaceBySlug } from '@/lib/db/repositories';
import { withAuth } from '@/core/auth';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const RequestSchema = z.object({
  workspaceSlug: z.string().min(1),
  to: z.string().email().or(z.literal('')).default(''),
  /** Optional: explizite Sender-Email. Falls leer → Workspace-Default (senderEmail). */
  senderEmail: z.string().email().optional(),
  senderName: z.string().optional(),
  subject: z.string().min(1),
  bodyHtml: z.string().min(50),
  bodyText: z.string().optional(),
  preheader: z.string().optional(),
});

/**
 * Test-Versand: schickt die generierte Email an EINE Test-Adresse über den
 * aktiven SendProvider (siehe adapters.config.ts).
 *
 * Default-Empfänger: M365_AUDIT_BCC env-var falls gesetzt, sonst Pflicht-Param `to`.
 * Verfälscht keine Statistiken — nur Validierung dass Rendering + Auth + Versand funktioniert.
 */
export const POST = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = RequestSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        {
          error: 'Invalid input',
          issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
        },
        { status: 400 },
      );
    }

    if (!adapters.send.isConfigured()) {
      return NextResponse.json(
        {
          error: `Send provider "${adapters.send.name}" not configured. Configure it via the Settings UI (send_provider_config) or set the matching env vars.`,
        },
        { status: 400 },
      );
    }

    const workspace = getWorkspaceBySlug(parsed.data.workspaceSlug);
    if (!workspace) {
      return NextResponse.json(
        { error: `Unknown workspace: ${parsed.data.workspaceSlug}` },
        { status: 400 },
      );
    }

    // Sender-Resolution: explizite senderEmail (User-Wahl) > Workspace-Default
    const fromEmail = parsed.data.senderEmail || workspace.senderEmail;
    const fromName = parsed.data.senderName || workspace.senderName || '';
    if (!fromEmail) {
      return NextResponse.json(
        {
          error: `No sender resolvable for workspace "${workspace.name}". Set workspaces.sender_email or pass senderEmail in the request.`,
        },
        { status: 400 },
      );
    }

    // Default-Empfänger: M365_AUDIT_BCC. Falls explizit "to" gesetzt, nutze das.
    const targetEmail = parsed.data.to || process.env.M365_AUDIT_BCC;
    if (!targetEmail) {
      return NextResponse.json(
        { error: 'Kein Test-Empfänger. Bitte "to" angeben oder M365_AUDIT_BCC setzen.' },
        { status: 400 },
      );
    }

    // Subject mit [TEST]-Prefix damit nicht versehentlich produktive Mails verteilt werden.
    const testSubject = parsed.data.subject.startsWith('[TEST]')
      ? parsed.data.subject
      : `[TEST] ${parsed.data.subject}`;

    const startedAt = Date.now();
    const result = await adapters.send.send({
      workspaceId: workspace.id,
      from: { email: fromEmail, name: fromName },
      to: [targetEmail],
      subject: testSubject,
      bodyHtml: parsed.data.bodyHtml,
      bodyText: parsed.data.bodyText ?? '',
    });
    const durationMs = Date.now() - startedAt;

    if (!result.ok) {
      const status =
        result.errorKind === 'config'
          ? 400
          : result.errorKind === 'network' || result.errorKind === 'auth'
            ? 502
            : 500;
      return NextResponse.json(
        {
          error: result.error ?? `Send failed (${result.errorKind ?? 'unknown'})`,
          errorKind: result.errorKind,
          httpStatus: result.httpStatus,
          provider: adapters.send.name,
        },
        { status },
      );
    }

    return NextResponse.json({
      ok: true,
      provider: adapters.send.name,
      sender: { email: fromEmail, name: fromName },
      to: targetEmail,
      subject: testSubject,
      durationMs,
      messageId: result.messageId,
      message: `Test-Mail gesendet von ${fromEmail} an ${targetEmail} (provider: ${adapters.send.name})`,
    });
  } catch (err) {
    console.error('[/api/send-test] error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error', errorKind: 'unknown' },
      { status: 500 },
    );
  }
});
