import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { getReminder, updateReminder, deleteReminder } from '@/lib/services/reminders.service';
import { updateReminderSchema } from '@/lib/validators/reminders';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('reminders', 'view_own', async (_req, ctx, params) => {
    try {
      const data = await getReminder(params.id!, ctx.portId);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('reminders', 'edit_own', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updateReminderSchema);
      const data = await updateReminder(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('reminders', 'edit_own', async (_req, ctx, params) => {
    try {
      await deleteReminder(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
