import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../../lib/permission-middleware';

export default async function handler(req, res) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    // Get authenticated user
    const user = await getUserFromRequest(req);
    if (!user) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    
    const currentUserId = user.userId;

    // Get all public collections for community discovery
    const result = await sql`
      SELECT DISTINCT
        c.*,
        u.email as creator_email,
        COUNT(cc.card_id) as card_count,
        COALESCE(SUM(cards.market_price * cc.quantity), 0) as total_value,
        cp.role as user_role,
        CASE 
          WHEN c.user_id = ${currentUserId} THEN 'owner'
          WHEN cp.role IS NOT NULL THEN cp.role
          ELSE NULL
        END as effective_role
      FROM collections c
      LEFT JOIN users u ON c.user_id = u.id
      LEFT JOIN collection_cards cc ON c.id = cc.collection_id
      LEFT JOIN cards ON cc.card_id = cards.id
      LEFT JOIN collection_permissions cp ON c.id = cp.collection_id AND cp.user_id = ${currentUserId} AND cp.status = 'active'
      WHERE c.is_public = true
      GROUP BY c.id, u.email, cp.role
      ORDER BY c.updated_at DESC
    `;

    const collections = result.rows.map(collection => ({
      id: collection.id,
      slug: collection.slug,
      name: collection.name,
      description: collection.description,
      tcg: collection.tcg || 'MTG',
      cardCount: parseInt(collection.card_count) || 0,
      value: parseFloat(collection.total_value) || 0,
      lastViewed: collection.updated_at,
      createdAt: collection.created_at,
      isPublic: collection.is_public || false,
      tags: collection.tags ? collection.tags.split(',') : [],
      creator: collection.creator_email,
      userRole: collection.effective_role
    }));

    res.status(200).json(collections);

  } catch (error) {
    console.error('Error fetching community collections:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
} 