import { NextResponse } from 'next/server';
import { db, languages } from '@/server/db/drizzle';
import { eq, asc } from 'drizzle-orm';

export async function GET() {
  try {
    /*
     * raw:
     * SELECT code, name, native_name, flag_emoji, is_rtl, is_default, display_order
     * FROM public.languages WHERE is_active = true ORDER BY display_order ASC, name ASC
     */
    const rows = await db.select({
      code: languages.code,
      name: languages.name,
      native_name: languages.nativeName,
      flag_emoji: languages.flagEmoji,
      is_rtl: languages.isRtl,
      is_default: languages.isDefault,
      display_order: languages.displayOrder,
    }).from(languages)
      .where(eq(languages.isActive, true))
      .orderBy(asc(languages.displayOrder), asc(languages.name));

    return NextResponse.json(
      { languages: rows },
      { headers: { 'Cache-Control': 'public, max-age=300, stale-while-revalidate=600' } }
    );
  } catch (err) {
    console.error('Public languages API error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
