import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { sendTestEmail } from '@/features/foundation/email/server/email-test.service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const sendTestEmailSchema = z.object({
  recipientEmail: z.string().trim().email(),
});

export async function POST(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsAdmin,
    });
    const { id } = await context.params;
    const payload = sendTestEmailSchema.parse(await request.json());

    return NextResponse.json(
      await sendTestEmail({
        organizationId: organization.id,
        userId: session.user.id,
        configurationId: id,
        recipientEmail: payload.recipientEmail,
      })
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: 'Invalid test email payload', errors: error.flatten() },
        { status: 400 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to send test email' }, { status: 500 });
  }
}
