import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody, parseQuery } from '@/lib/api/route-helpers';
import { listReminders, createReminder } from '@/lib/services/reminders.service';
import { reminderListQuerySchema, createReminderSchema } from '@/lib/validators/reminders';
import { errorResponse, ForbiddenError } from '@/lib/errors';

export const GET = withAuth(
  withPermission('reminders', 'view_own', async (req, ctx) => {
    try {
      const query = parseQuery(req, reminderListQuerySchema);
      const result = await listReminders(ctx.portId, query);
      // L34 carve-out: deliberate bare-shape response (NOT the `{ data }`
      // envelope). The reminders consumers read the fields off the JSON
      // root; wrapping them would break them. Left as-is. (The POST below
      // already uses the canonical `{ data }` envelope.)
      return NextResponse.json(result);
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('reminders', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createReminderSchema);

      // Check assign_others permission if assigning to someone else
      if (body.assignedTo && body.assignedTo !== ctx.userId) {
        if (!ctx.isSuperAdmin && !ctx.permissions?.reminders?.assign_others) {
          throw new ForbiddenError('Cannot assign reminders to other users');
        }
      }

      const data = await createReminder(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
