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

export async function GET(request: Request) {
  const db = getDatabase();
  const { searchParams } = new URL(request.url);
  const limit = parseInt(searchParams.get('limit') || '50');
  const offset = parseInt(searchParams.get('offset') || '0');
  const search = searchParams.get('search');

  try {
    let query = `
      SELECT m.*, l.path as library_path 
      FROM media m 
      JOIN libraries l ON m.library_id = l.id 
      WHERE m.type = 'text'
    `;
    let params: any[] = [];

    if (search) {
      query += ' AND (m.title LIKE ? OR m.path LIKE ?)';
      params.push(`%${search}%`, `%${search}%`);
    }

    query += ' ORDER BY m.created_at DESC LIMIT ? OFFSET ?';
    params.push(limit, offset);

    const texts = db.prepare(query).all(...params) as { id: number; title: string; path: string; size: number; thumbnail: string; type: string; bookmark_count: number; avg_rating: number; star_count: number; library_path: string; created_at: string }[];

    const totalQuery = `
      SELECT COUNT(*) as count 
      FROM media m 
      WHERE m.type = 'text'
      ${search ? 'AND (m.title LIKE ? OR m.path LIKE ?)' : ''}
    `;
    const totalParams = search ? [`%${search}%`, `%${search}%`] : [];
    const total = (db.prepare(totalQuery).get(...totalParams) as { count: number }).count;

    return NextResponse.json({
      texts,
      pagination: {
        total,
        limit,
        offset,
        hasMore: offset + limit < total
      }
    });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function POST(request: Request) {
  const { mediaId } = await request.json();
  
  try {
    const db = getDatabase();
    const text = db.prepare('SELECT * FROM media WHERE id = ? AND type = "text"').get(mediaId) as { id: number; path: string; title: string; size: number };
    
    if (!text) {
      return NextResponse.json({ error: 'Text file not found' }, { status: 404 });
    }

    const content = fs.readFileSync(text.path, 'utf-8');
    
    return NextResponse.json({
      id: text.id,
      title: text.title,
      path: text.path,
      content,
      size: text.size
    });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}