import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { z } from 'zod';
import { db, phoneNumbers } from '@server/db/drizzle';
import { eq, and, sql } from 'drizzle-orm';
import { ValidationError } from '@server/errors';
import { provisionWebhookForNumber } from '@server/services/telephone/twilio-phone.service';

const toggleSchema = z.object({
  number_id: z.string().uuid(),
  is_active: z.boolean(),
});

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(toggleSchema, async (req) => {
      const { number_id, is_active } = req.parsedBody as { number_id: string; is_active: boolean };

      const result = await db.update(phoneNumbers)
        .set({ isActive: is_active, updatedAt: sql`NOW()` })
        .where(and(eq(phoneNumbers.id, number_id), eq(phoneNumbers.restaurantId, req.session.restaurantId!)));

      if ((result.rowCount ?? 0) === 0) throw new ValidationError('Phone number not found');
      await provisionWebhookForNumber(number_id, req.session.restaurantId!);
      return NextResponse.json({ success: true });
    })
  )
);
