import { NextResponse } from 'next/server';

import { withAuth } from '@/lib/api/helpers';
import { getEmailDraftResult } from '@/lib/services/email-draft.service';
import { errorResponse, ValidationError } from '@/lib/errors';

export const GET = withAuth(async (_req, ctx, params) => {
  try {
    const { jobId } = params;
    if (!jobId) throw new ValidationError('jobId is required');

    const result = await getEmailDraftResult(jobId, {
      userId: ctx.userId,
      portId: ctx.portId,
    });

    if (result === null) {
      return NextResponse.json({ status: 'processing' });
    }

    return NextResponse.json({ status: 'complete', data: result });
  } catch (error) {
    return errorResponse(error);
  }
});
