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

import { childLogger } from '@server/logger';
import { wrapRouteHandler } from '@server/logger/request';
const log = childLogger('route.public.languages');

async function handleGET() {
  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) {
    log.error({ err }, 'public languages API error');
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export const GET = wrapRouteHandler(handleGET);
