import { NextResponse } from 'next/server';
import { previewDocumentTemplateVersion } from '@/features/foundation/document-template/server/management-service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string }>;
};

export async function GET(_request: Request, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateRead,
    });
    const preview = await previewDocumentTemplateVersion({
      versionId: id,
      organizationId: organization.id,
    });

    return NextResponse.json({
      success: true,
      message: 'Document template preview generated successfully',
      preview,
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { message: 'Unable generate document template preview' },
      { status: 500 },
    );
  }
}
