import { NextRequest, NextResponse } from 'next/server';

import loadEnv from '../handler/load-env';
import syncConnectedOnline from '../handler/sync-connected-online';
import validateApiKey from '../handler/validate-api-key';

export const POST = async (request: NextRequest) => {
  loadEnv();

  try {
    validateApiKey(request);
  } catch (e) {
    return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
  }

  try {
    await syncConnectedOnline();
    console.info('Successfully synced connected-online');
    return NextResponse.json(
      {
        message: 'Successfully synced connected-online',
      },
      { status: 200 },
    );
  } catch (e) {
    console.error('Error syncing connected-online', e);
    return NextResponse.json(
      {
        message: 'Failed to sync connected-online',
      },
      { status: 500 },
    );
  }
};
