import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate } from '@/features/foundation/audit-log/service';
import {
  createDocumentSequence,
  listDocumentSequences
} from '@/features/foundation/document-sequence/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

export async function GET(_request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentSequenceRead
    });
    const items = await listDocumentSequences(organization.id);

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

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentSequenceCreate
    });
    const payload = sequenceSchema.parse(await request.json());
    const created = await createDocumentSequence(organization.id, payload);

    await auditCreate({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_document_sequence',
      entityId: created.id,
      afterData: created
    });

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