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, NotFoundError } from '@/lib/errors';
import { getPortReminderConfig } from '@/lib/services/port-config';
import { updateUserPreferencesSchema } from '@/lib/validators/user-preferences';

export const GET = withAuth(async (_req, ctx) => {
  try {
    const [profile, portReminders] = await Promise.all([
      db.query.userProfiles.findFirst({ where: eq(userProfiles.userId, ctx.userId) }),
      ctx.portId ? getPortReminderConfig(ctx.portId) : Promise.resolve(null),
    ]);
    return NextResponse.json({
      data: {
        ...(profile?.preferences ?? {}),
        portReminderDigestEnabled: portReminders?.digestEnabled ?? false,
      },
    });
  } 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) throw new NotFoundError('profile');

    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);
  }
});
