import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  getM365Senders,
  getActiveM365Senders,
  setM365Senders,
} from '@/lib/db/repositories';
import type { M365Sender } from '@/lib/db/defaults';
import { withAuth } from '@/core/auth';

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

/**
 * GET /api/m365/senders?includeInactive=1
 * Liefert die konfigurierten Absender-Mailboxen für UI-Dropdowns.
 */
export const GET = withAuth(async (req: NextRequest, _ctx) => {
  const includeInactive = req.nextUrl.searchParams.get('includeInactive') === '1';
  const senders = includeInactive ? getM365Senders() : getActiveM365Senders();
  return NextResponse.json({ ok: true, senders });
});

const SenderSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1),
  companyId: z.number().int().positive().optional(),
  active: z.boolean().default(true),
  note: z.string().optional(),
});

const PostSchema = z.object({
  /** Vollständige Liste (replace-all). Leeres Array = Pool leeren (UI erlaubt „alle Zeilen entfernen“). */
  senders: z.array(SenderSchema),
});

/**
 * POST /api/m365/senders
 * Replace-all-Update der Sender-Liste. Validiert Email-Format + Pflichtfelder.
 */
export const POST = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = PostSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        {
          error: 'Invalid input',
          issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
        },
        { status: 400 },
      );
    }
    // Dedupe per email (case-insensitive) — erste Definition gewinnt
    const seen = new Set<string>();
    const deduped: M365Sender[] = [];
    for (const s of parsed.data.senders) {
      const key = s.email.toLowerCase();
      if (seen.has(key)) continue;
      seen.add(key);
      deduped.push({ ...s, email: key });
    }
    setM365Senders(deduped);
    return NextResponse.json({ ok: true, senders: deduped });
  } catch (e) {
    return NextResponse.json(
      { error: e instanceof Error ? e.message : 'Internal error' },
      { status: 500 },
    );
  }
});
