import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateSipLineSchema } from '@server/validators/telephone.validator';
import { getSipLine, updateSipLine, deleteSipLine } from '@server/services/telephone/sip.service';
import { RouteContext } from '@server/middleware/withErrorHandler';

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

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateSipLineSchema, async (req, ctx) => {
      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(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    await deleteSipLine(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
