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

const VIDEO_EXTENSIONS = ["mp4", "mkv", "avi", "mov", "wmv", "flv", "webm", "m4v"];
const PHOTO_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "svg"];

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 files = fs.readdirSync(dirPath);
    
    // Get media files from database for this path
    const mediaFiles = db.prepare(`
      SELECT path, type, thumbnail 
      FROM media 
      WHERE path LIKE ?
    `).all(`${dirPath}%`) as Array<{path: string, type: string, thumbnail: string | null}>;

    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';
      if (VIDEO_EXTENSIONS.some(v => ext.includes(v))) {
        type = 'video';
      } else if (PHOTO_EXTENSIONS.some(p => ext.includes(p))) {
        type = 'photo';
      }

      // 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,
      };
    });

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