import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  deleteDocumentSequence,
  getDocumentSequence,
  updateDocumentSequence
} 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 }>;
};

const sequenceSchema = z.object({
  documentType: z.string().min(1).optional(),
  prefix: z.string().min(1).optional(),
  period: z.string().min(1).optional(),
  branchId: z.string().optional().nullable(),
  currentNumber: z.number().int().min(0).optional(),
  paddingLength: z.number().int().min(1).optional(),
  isActive: z.boolean().optional()
});

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentSequenceRead
    });
    const sequence = await getDocumentSequence(id, organization.id);

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

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentSequenceUpdate
    });
    const payload = sequenceSchema.parse(await request.json());
    const before = await getDocumentSequence(id, organization.id);
    const updated = await updateDocumentSequence(id, organization.id, payload);

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

    return NextResponse.json({
      success: true,
      message: 'Document sequence 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 sequence' }, { status: 500 });
  }
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentSequenceUpdate
    });
    const before = await getDocumentSequence(id, organization.id);
    const deleted = await deleteDocumentSequence(id, organization.id);

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

    return NextResponse.json({
      success: true,
      message: 'Document sequence 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 sequence' }, { status: 500 });
  }
}
