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 { updateSipLineSchema } from '@server/validators/sip.validator';
import { getSipLine, updateSipLine, deleteSipLine } from '@server/services/telephone/sip/sip.service';
import { RouteContext } from '@server/middleware/withErrorHandler';

export const GET = withErrorHandler(
  withAuth(
    withSipFeatureAuthed(async (req: AuthedRequest, ctx: RouteContext) => {
      await requireSection(req, 'telephone');
      const { id } = await ctx.params;
      const line = await getSipLine(id, req.session.restaurantId!);
      return NextResponse.json({ line });
    })
  )
);

export const PATCH = withErrorHandler(
  withAuth(
    withSipFeatureAuthed(
      withValidationAuthed(updateSipLineSchema, async (req, ctx) => {
        await requireSection(req, 'telephone', 'update');
        const { id } = await ctx.params;
        const line = await updateSipLine(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
        return NextResponse.json({ line });
      })
    )
  )
);

export const DELETE = withErrorHandler(
  withAuth(
    withSipFeatureAuthed(async (req: AuthedRequest, ctx: RouteContext) => {
      await requireSection(req, 'telephone', 'delete');
      const { id } = await ctx.params;
      await deleteSipLine(id, req.session.restaurantId!);
      return NextResponse.json({ success: true });
    })
  )
);
