import { getInternalGenerationHeaders } from '@/lib/server-api-config';

export type GenerationJobType = 'image' | 'video';

export async function runGenerationPayload(
  type: GenerationJobType,
  payload: Record<string, unknown>,
  options: { userId?: string | null; jobId?: string | null } = {},
) {
  const port = process.env.PORT || process.env.DEPLOY_RUN_PORT || '5000';
  const baseUrl = process.env.GENERATION_INTERNAL_BASE_URL || `http://127.0.0.1:${port}`;
  const endpoint = type === 'image' ? '/api/generate/image' : '/api/generate/video';
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...getInternalGenerationHeaders(),
  };
  if (options.userId) headers['x-miaojing-generation-user-id'] = options.userId;
  if (options.jobId) headers['x-miaojing-generation-job-id'] = options.jobId;

  const res = await fetch(`${baseUrl}${endpoint}`, {
    method: 'POST',
    headers,
    body: JSON.stringify(payload),
  });
  const data = await res.json().catch(() => ({}));

  if (!res.ok) {
    throw new Error(
      typeof data?.error === 'string'
        ? data.error
        : `Generation request failed (${res.status})`,
    );
  }

  return data;
}
