import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { renameFolderSchema, moveFolderSchema } from '@/lib/validators/document-folders';
import {
  renameFolder,
  moveFolder,
  deleteFolderSoftRescue,
} from '@/lib/services/document-folders.service';

/**
 * PATCH supports either { name } (rename) or { parentId } (move).
 * Refuses both in the same body - keeps the audit log clean
 * (one operation per call) and prevents the rep from accidentally
 * doing two unrelated changes in one click.
 */
// `.strict()` on each branch so a body with BOTH name and parentId is
// rejected by both members and the union produces a 400 - without it,
// z.union silently picks the first match and drops the other key,
// which would let a rename request silently swallow a move attempt.
const patchBodySchema = z.union([renameFolderSchema.strict(), moveFolderSchema.strict()]);

export const PATCH = withAuth(
  withPermission('documents', 'manage_folders', async (req, ctx, params) => {
    try {
      const folderId = params.id;
      if (!folderId) throw new NotFoundError('Folder');
      const body = await parseBody(req, patchBodySchema);
      let updated;
      if ('name' in body) {
        updated = await renameFolder(ctx.portId, folderId, body.name, ctx.userId);
      } else {
        updated = await moveFolder(ctx.portId, folderId, body.parentId, ctx.userId);
      }
      return NextResponse.json({ data: updated });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('documents', 'manage_folders', async (_req, ctx, params) => {
    try {
      const folderId = params.id;
      if (!folderId) throw new NotFoundError('Folder');
      await deleteFolderSoftRescue(ctx.portId, folderId, ctx.userId);
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
