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 } from '@/lib/errors';
import {
  deleteReportTemplate,
  getReportTemplate,
  updateReportTemplate,
} from '@/lib/services/report-templates.service';

const patchBodySchema = z
  .object({
    name: z.string().min(1).max(120).optional(),
    description: z.string().max(400).nullable().optional(),
    config: z.record(z.string(), z.unknown()).optional(),
  })
  .refine((v) => v.name !== undefined || v.description !== undefined || v.config !== undefined, {
    message: 'At least one field must be provided',
  });

/**
 * GET    - single template (used by the dialog to hydrate a saved
 *          template into the form when the rep picks it).
 * PATCH  - rename, retitle, or rewrite the config.
 * DELETE - remove. Cascade-safe: no FKs reference a saved template.
 */
export const GET = withAuth(
  withPermission('reports', 'export', async (_req, ctx, params) => {
    try {
      const row = await getReportTemplate(params.id!, ctx.portId);
      return NextResponse.json({ data: row });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('reports', 'export', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, patchBodySchema);
      const row = await updateReportTemplate({
        id: params.id!,
        portId: ctx.portId,
        name: body.name,
        description: body.description,
        config: body.config,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });
      return NextResponse.json({ data: row });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('reports', 'export', async (_req, ctx, params) => {
    try {
      await deleteReportTemplate(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);
    }
  }),
);
