./kaisetsu-app/src/app/api/analyze/status/route.ts

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

export const dynamic = 'force-dynamic';

interface JobStatus {
  status: 'processing' | 'completed' | 'error';
  step: string;
  progress: number;
  error?: string;
  createdAt: string;
  updatedAt: string;
}

export async function GET(request: NextRequest) {
  const jobId = request.nextUrl.searchParams.get('jobId');

  if (!jobId) {
    return NextResponse.json({ error: 'jobId is required' }, { status: 400 });
  }

  try {
    const status = await storage.getJobStatus<JobStatus>(jobId);
    if (!status) {
      return NextResponse.json({ error: 'Job not found' }, { status: 404 });
    }

    if (status.status === 'processing' && status.updatedAt) {
      const elapsed = Date.now() - new Date(status.updatedAt).getTime();
      if (elapsed > 15 * 60 * 1000) {
        return NextResponse.json({
          ...status,
          status: 'error',
          error: 'Processing timed out (no update for 15 minutes)',
        });
      }
    }

    if (status.status === 'completed') {
      const result = await storage.getJobResult<Record<string, unknown>>(jobId);
      if (result) {
        return NextResponse.json({ ...status, ...result });
      }
    }

    return NextResponse.json(status);
  } catch (error) {
    console.error('Status check error:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Status check failed' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  const { jobId, format } = await request.json();
  if (!jobId) {
    return NextResponse.json({ error: 'jobId is required' }, { status: 400 });
  }

  try {
    const result = await storage.getJobResult<Record<string, unknown>>(jobId);
    if (!result) {
      return NextResponse.json({ error: 'Result not found' }, { status: 404 });
    }

    if (format === 'json') {
      return new NextResponse(JSON.stringify(result, null, 2), {
        headers: {
          'Content-Type': 'application/json',
          'Content-Disposition': `attachment; filename="kaisetsu-result-${jobId.substring(0, 8)}.json"`,
        },
      });
    }

    return NextResponse.json(result);
  } catch (error) {
    console.error('Result download error:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Download failed' },
      { status: 500 }
    );
  }
}