import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { withSipFeatureAuthed } from '@server/middleware/withSipFeature';
import { createSipLineSchema } from '@server/validators/sip.validator';
import { listSipLines, createSipLine } from '@server/services/telephone/sip/sip.service';

export const GET = withErrorHandler(
  withAuth(
    withSipFeatureAuthed(async (req: AuthedRequest) => {
      await requireSection(req, 'telephone');
      const lines = await listSipLines(req.session.restaurantId!);
      return NextResponse.json({ lines });
    })
  )
);

export const POST = withErrorHandler(
  withAuth(
    withSipFeatureAuthed(
      withValidationAuthed(createSipLineSchema, async (req) => {
        await requireSection(req, 'telephone', 'create');
        const line = await createSipLine(req.session.restaurantId!, req.parsedBody as Parameters<typeof createSipLine>[1]);
        return NextResponse.json({ line }, { status: 201 });
      })
    )
  )
);
