import { eq } from 'drizzle-orm';
import { NextResponse } from 'next/server';

import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { db } from '@/lib/db';
import { userProfiles, type UserPreferences } from '@/lib/db/schema/users';
import { errorResponse } from '@/lib/errors';
import { updateUserPreferencesSchema } from '@/lib/validators/user-preferences';

export const GET = withAuth(async (_req, ctx) => {
  try {
    const profile = await db.query.userProfiles.findFirst({
      where: eq(userProfiles.userId, ctx.userId),
    });
    return NextResponse.json({ data: profile?.preferences ?? {} });
  } catch (error) {
    return errorResponse(error);
  }
});

export const PATCH = withAuth(async (req, ctx) => {
  try {
    const patch = await parseBody(req, updateUserPreferencesSchema);

    const profile = await db.query.userProfiles.findFirst({
      where: eq(userProfiles.userId, ctx.userId),
    });
    if (!profile) {
      return NextResponse.json({ error: 'Profile not found' }, { status: 404 });
    }

    const next: UserPreferences = {
      ...(profile.preferences ?? {}),
      ...patch,
    };

    await db
      .update(userProfiles)
      .set({ preferences: next })
      .where(eq(userProfiles.userId, ctx.userId));

    return NextResponse.json({ data: next });
  } catch (error) {
    return errorResponse(error);
  }
});
