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

export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  try {
    const parsedId = parseInt(id);
    
    if (isNaN(parsedId)) {
      return NextResponse.json({ error: 'Invalid star ID' }, { status: 400 });
    }

    // Get media_id before deleting
    const star = db.prepare(`
      SELECT media_id FROM stars WHERE id = ?
    `).get(parsedId) as { media_id: number } | undefined;

    if (!star) {
      return NextResponse.json({ error: 'Star rating not found' }, { status: 404 });
    }

    // Delete star rating
    db.prepare(`DELETE FROM stars WHERE id = ?`).run(parsedId);

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

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