import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ValidationError } from '@server/errors';
import { listTemplates, bulkUpsertTemplates } from '@server/services/templates.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const templates = await listTemplates(req.session.restaurantId!);
    return NextResponse.json({ templates });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    let body: Awaited<ReturnType<typeof req.json>>;
    try {
      body = await req.json();
    } catch {
      throw new ValidationError('Request body must be valid JSON');
    }
    const { templates } = body;
    if (!Array.isArray(templates)) {
      return NextResponse.json({ error: 'templates must be an array' }, { status: 400 });
    }
    const saved = await bulkUpsertTemplates(
      req.session.restaurantId!,
      templates.map((t: { templateKey: string; channel: string; content: string }) => ({
        templateKey: t.templateKey,
        channel: t.channel,
        content: t.content,
      }))
    );
    return NextResponse.json({ templates: saved });
  })
);
