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

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const mediaId = searchParams.get('mediaId');

    if (mediaId) {
      // Get stars for specific media
      const stars = db.prepare(`
        SELECT * FROM stars WHERE media_id = ?
        ORDER BY created_at DESC
      `).all(parseInt(mediaId));
      
      return NextResponse.json(stars);
    } else {
      // Get all stars
      const stars = db.prepare(`
        SELECT m.*, l.path as library_path, s.rating
        FROM stars s
        JOIN media m ON s.media_id = m.id
        JOIN libraries l ON m.library_id = l.id
        ORDER BY s.created_at DESC
      `).all();

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

export async function POST(request: Request) {
  try {
    const { mediaId, rating } = await request.json();

    if (!mediaId || !rating) {
      return NextResponse.json({ error: 'mediaId and rating are required' }, { status: 400 });
    }

    if (rating < 1 || rating > 5) {
      return NextResponse.json({ error: 'Rating must be between 1 and 5' }, { status: 400 });
    }

    // Check if already starred
    const existing = db.prepare(`
      SELECT id FROM stars WHERE media_id = ?
    `).get(mediaId);

    if (existing) {
      // Update existing star rating
      db.prepare(`
        UPDATE stars 
        SET rating = ?, updated_at = CURRENT_TIMESTAMP
        WHERE media_id = ?
      `).run(rating, mediaId);
    } else {
      // Insert new star rating
      db.prepare(`
        INSERT INTO stars (media_id, rating) VALUES (?, ?)
      `).run(mediaId, rating);
    }

    // Update media star count and average rating
    db.prepare(`
      UPDATE media 
      SET 
        star_count = (SELECT COUNT(*) FROM stars WHERE media_id = ?),
        avg_rating = (SELECT AVG(rating) FROM stars WHERE media_id = ?)
      WHERE id = ?
    `).run(mediaId, mediaId, mediaId);

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