import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  deleteDocumentTemplateMapping,
  updateDocumentTemplateMapping
} from '@/features/foundation/document-template/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const columnSchema = z.object({
  columnName: z.string().min(1),
  sourceField: z.string().min(1),
  columnLetter: z.string().optional().nullable(),
  sortOrder: z.number().int().optional(),
  formatMask: z.string().optional().nullable()
});

const mappingSchema = z.object({
  placeholderKey: z.string().min(1).optional(),
  sourcePath: z.string().min(1).optional(),
  dataType: z.enum(['scalar', 'multiline', 'table', 'image']).optional(),
  sheetName: z.string().optional().nullable(),
  defaultValue: z.string().optional().nullable(),
  formatMask: z.string().optional().nullable(),
  sortOrder: z.number().int().optional(),
  columns: z.array(columnSchema).optional()
});

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateUpdate
    });
    const payload = mappingSchema.parse(await request.json());
    const updated = await updateDocumentTemplateMapping(id, organization.id, payload);

    await auditUpdate({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_document_template_mapping',
      entityId: id,
      afterData: updated
    });

    return NextResponse.json({
      success: true,
      message: 'Document template mapping updated successfully'
    });
  } 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.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }
    return NextResponse.json(
      { message: 'Unable to update document template mapping' },
      { status: 500 }
    );
  }
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateDelete
    });
    const result = await deleteDocumentTemplateMapping(id, organization.id);

    await auditDelete({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_document_template_mapping',
      entityId: id,
      beforeData: result.before,
      afterData: result.after
    });

    return NextResponse.json({
      success: true,
      message: 'Document template mapping deleted successfully'
    });
  } 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 delete document template mapping' },
      { status: 500 }
    );
  }
}
