import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { withSipFeatureAuthed } from '@server/middleware/withSipFeature';
import { testSipConnectionSchema } from '@server/validators/sip.validator';
import { testSipConnection } from '@server/services/telephone/sip/sip-test.service';

export const POST = withErrorHandler(
  withAuth(
    withSipFeatureAuthed(
      withValidationAuthed(testSipConnectionSchema, async (req) => {
        await requireSection(req, 'telephone');
        const body = req.parsedBody as Parameters<typeof testSipConnection>[1];
        const result = await testSipConnection(req.session.restaurantId!, body);
        return NextResponse.json(result, { status: result.ok ? 200 : 400 });
      })
    )
  )
);
