import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
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) => {
    const body = await req.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 });
  })
);
