import { NextRequest, NextResponse } from 'next/server';
import { previewDocumentSequenceById } from '@/features/foundation/document-sequence/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: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentSequenceRead
    });
    const preview = await previewDocumentSequenceById(id, organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Document sequence preview loaded 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 to preview document sequence' },
      { status: 500 }
    );
  }
}
