import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ValidationError } from '@server/errors';
import { eq, and } from 'drizzle-orm';
import { db, users, languages } from '@server/db/drizzle';

export const PATCH = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const body = await req.json() as { lang: string };
    const { lang } = body;
    if (!lang || typeof lang !== 'string' || !/^[a-z]{2,8}(-[a-z0-9]{2,8})?$/.test(lang)) {
      throw new ValidationError('Invalid language code');
    }

    const langRows = await db
      .select({ code: languages.code })
      .from(languages)
      .where(and(eq(languages.code, lang), eq(languages.isActive, true)));
    if (langRows.length === 0) {
      throw new ValidationError('Language not found or not active');
    }

    await db.update(users).set({ preferredLanguage: lang }).where(eq(users.id, req.session.userId));

    return NextResponse.json({ ok: true, lang });
  })
);
