import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { compareDocumentTemplateVersions } 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 }>;
};

const compareSchema = z.object({
  leftVersionId: z.string().min(1),
  rightVersionId: z.string().min(1),
});

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateRead,
    });
    const payload = compareSchema.parse(await request.json());
    const comparison = await compareDocumentTemplateVersions({
      templateId: id,
      leftVersionId: payload.leftVersionId,
      rightVersionId: payload.rightVersionId,
      organizationId: organization.id,
    });

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

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

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

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