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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    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) => {
      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 disconnectTwilio(req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
