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

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;

    return NextResponse.json(
      await testEmailConfigurationConnection({
        organizationId: organization.id,
        userId: session.user.id,
        configurationId: id,
      })
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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