
import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { getDatabase } from '@/db';

const VIDEO_EXTENSIONS = ["mp4", "mkv", "avi", "mov", "wmv", "flv", "webm", "m4v"];
const PHOTO_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "svg"];
const TEXT_EXTENSIONS = ["txt", "md", "json", "xml", "csv", "log", "conf", "ini", "yaml", "yml", "html", "css", "js", "ts", "py", "sh", "bat", "php", "sql"];

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const dirPath = searchParams.get("path");

  if (!dirPath) {
    return NextResponse.json({ error: "Path is required" }, { status: 400 });
  }

  try {
    const db = getDatabase();
    const files = fs.readdirSync(dirPath);
    
    // Get media files from database for this path
    const mediaFiles = db.prepare(`
      SELECT id, path, type, thumbnail, avg_rating, star_count
      FROM media 
      WHERE path LIKE ?
    `).all(`${dirPath}%`) as Array<{id: number, path: string, type: string, thumbnail: string | null, avg_rating: number, star_count: number}>;

    const result = files.map((file) => {
      const filePath = path.join(dirPath, file);
      const stats = fs.statSync(filePath);
      const ext = path.extname(file).toLowerCase();
      
      let type = 'file';
      const cleanExt = ext.replace('.', '').toLowerCase();
      if (VIDEO_EXTENSIONS.some(v => v.toLowerCase() === cleanExt)) {
        type = 'video';
      } else if (PHOTO_EXTENSIONS.some(p => p.toLowerCase() === cleanExt)) {
        type = 'photo';
      } else if (TEXT_EXTENSIONS.some(t => t.toLowerCase() === cleanExt)) {
        type = 'text';
      }

        // Find matching media file in database
      const mediaFile = mediaFiles.find((m: any) => m.path === filePath);

      return {
        name: file,
        path: filePath,
        isDirectory: stats.isDirectory(),
        size: stats.size,
        type: mediaFile?.type || type,
        thumbnail: mediaFile?.thumbnail,
        id: mediaFile?.id,
        avg_rating: mediaFile?.avg_rating || 0,
        star_count: mediaFile?.star_count || 0,
      };
    });

    return NextResponse.json(result);
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
