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

const documentTemplateSchema = z.object({
  documentType: z.string().min(1),
  productType: z.string().min(1),
  fileType: z.string().min(1),
  templateName: z.string().min(1),
  description: z.string().optional().nullable(),
  isDefault: z.boolean().optional(),
  isActive: z.boolean().optional()
});

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateRead
    });
    const { searchParams } = request.nextUrl;
    const items = await listDocumentTemplates(organization.id, {
      documentType: searchParams.get('documentType') ?? undefined,
      fileType: searchParams.get('fileType') ?? undefined,
      isActive: searchParams.get('isActive') ?? undefined
    });

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

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

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

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