/**
 * Detail-Endpoint für ein Trigger-Template.
 *   GET    /api/trigger-templates/{id}        — Detail-View
 *   PATCH  /api/trigger-templates/{id}        — Activate/Deactivate
 *
 * Aus Sicherheitsgründen können wir das Template nicht „bearbeiten" (Subject/MJML),
 * weil dann die Snapshot-Garantie der Container-Campaign bricht. Wer Inhalt
 * ändern will, schaltet ein neues Template frei und deaktiviert das alte.
 */

import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  getTriggerTemplateById,
  setTriggerTemplateActive,
} from '@/lib/db/trigger-template-repo';
import { withAuth } from '@/core/auth';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const PatchSchema = z.object({
  isActive: z.boolean(),
});

export const GET = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const t = getTriggerTemplateById(id);
  if (!t) return NextResponse.json({ error: 'Template not found' }, { status: 404 });
  // apiKeyHash wird NIE rausgegeben — apiKeyPrefix reicht für die UI-Darstellung.
  const { apiKeyHash, ...safe } = t;
  void apiKeyHash;
  return NextResponse.json({ template: safe });
});

export const PATCH = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const t = getTriggerTemplateById(id);
  if (!t) return NextResponse.json({ error: 'Template not found' }, { status: 404 });

  const raw = await req.json();
  const parsed = PatchSchema.safeParse(raw);
  if (!parsed.success) {
    return NextResponse.json({
      error: 'Validation failed',
      issues: parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`),
    }, { status: 400 });
  }

  setTriggerTemplateActive(id, parsed.data.isActive);
  return NextResponse.json({ ok: true, isActive: parsed.data.isActive });
});
