import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getFileUrl } from '@/lib/minio';

export async function GET() {
  try {
    const videos = await prisma.video.findMany({
      orderBy: { created_at: 'desc' },
      take: 1000,
      include: {
        author: {
          select: {
            nickname: true,
          },
        },
        transcript: {
          select: {
            id: true,
            speech_detected: true,
            language: true,
            audio_type: true,
            transcript: true,
            non_speech_summary: true,
          },
        },
      },
    });

    const formattedVideos = videos.map((v) => ({
      aweme_id: v.aweme_id,
      desc: v.desc,
      cover_url: getFileUrl(v.cover_url ?? ''),
      duration_ms: v.duration_ms,
      author: {
        nickname: v.author.nickname,
      },
      transcript: v.transcript
        ? {
            id: v.transcript.id,
            speech_detected: v.transcript.speech_detected,
            language: v.transcript.language,
            audio_type: v.transcript.audio_type,
            transcript: v.transcript.transcript,
            non_speech_summary: v.transcript.non_speech_summary,
          }
        : null,
    }));

    return NextResponse.json({
      videos: formattedVideos,
      total: videos.length,
    });
  } catch (error) {
    console.error('Failed to fetch videos:', error);
    return NextResponse.json(
      { error: 'Failed to fetch videos' },
      { status: 500 }
    );
  }
}
