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

import loadEnv from '../handler/load-env';
import syncAnalysisResults from '../handler/sync-analysis-results';
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 syncAnalysisResults();
    console.info('Successfully synced analysis results');
    return NextResponse.json(
      {
        message: 'Successfully synced analysis results',
      },
      { status: 200 },
    );
  } catch (e) {
    console.error('Error syncing analysis results', e);
    return NextResponse.json(
      {
        message: 'Failed to sync analysis results',
      },
      { status: 500 },
    );
  }
};
