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 { twilioConnectSchema } from '@server/validators/telephone.validator';
import { getValidatedSettings, saveTwilioCredentials, disconnectTwilio, listPhoneNumbers, fetchAndSyncTwilioNumbers } from '@server/services/telephone/twilio-phone.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'telephone');
    await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
    const { settings, valid } = await getValidatedSettings(req.session.restaurantId!);
    const numbers = await listPhoneNumbers(req.session.restaurantId!);

    if (valid) {
      await fetchAndSyncTwilioNumbers(req.session.restaurantId!);
      const updatedNumbers = await listPhoneNumbers(req.session.restaurantId!);
      return NextResponse.json({ settings, numbers: updatedNumbers });
    }

    return NextResponse.json({ settings, numbers });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(twilioConnectSchema, async (req) => {
      await requireSection(req, 'telephone', 'create');
      await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
      const { account_sid, auth_token } = req.parsedBody as { account_sid: string; auth_token: string };
      const result = await saveTwilioCredentials(req.session.restaurantId!, account_sid, auth_token);
      if (!result.connected) {
        return NextResponse.json({ error: result.error, connected: false }, { status: 400 });
      }
      return NextResponse.json({ connected: true });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'telephone', 'delete');
    await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
    await disconnectTwilio(req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
