import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, NotFoundError } from '@server/errors';
import { db, languages, translations, translationKeys } from '@server/db/drizzle';
import { eq, and, sql, asc } from 'drizzle-orm';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: { params: Promise<Record<string, string>> }) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const { langCode } = await context.params;

    /*
     * raw:
     * SELECT code, name, native_name, flag_emoji, is_rtl
     * FROM public.languages WHERE code = $1
     */
    const langRows = await db
      .select({
        code: languages.code,
        name: languages.name,
        native_name: languages.nativeName,
        flag_emoji: languages.flagEmoji,
        is_rtl: languages.isRtl,
      })
      .from(languages)
      .where(eq(languages.code, langCode));

    if (langRows.length === 0) throw new NotFoundError('Language not found');
    const language = langRows[0];

    /*
     * raw:
     * SELECT tk.key, COALESCE(t.value, '') AS value
     * FROM public.translation_keys tk
     * LEFT JOIN public.translations t ON t.key_id = tk.id AND t.lang_code = $1
     * ORDER BY tk.key ASC
     */
    const rows = await db
      .select({
        key: translationKeys.key,
        value: sql<string>`COALESCE(${translations.value}, '')`,
      })
      .from(translationKeys)
      .leftJoin(
        translations,
        and(eq(translations.keyId, translationKeys.id), eq(translations.langCode, langCode))
      )
      .orderBy(asc(translationKeys.key));

    const translationMap: Record<string, string> = {};
    for (const row of rows) {
      translationMap[row.key] = row.value;
    }

    const payload = {
      version: 1,
      exported_at: new Date().toISOString(),
      language: {
        code: language.code,
        name: language.name,
        native_name: language.native_name,
        flag_emoji: language.flag_emoji,
        is_rtl: language.is_rtl,
      },
      translations: translationMap,
    };

    const json = JSON.stringify(payload, null, 2);
    const filename = `${langCode}-translations.json`;

    return new NextResponse(json, {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Content-Disposition': `attachment; filename="${filename}"`,
        'Cache-Control': 'no-store',
      },
    });
  })
);
