import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  createDocumentLibrary,
  listDocumentLibraries
} from '@/features/foundation/document-library/server/service';
import {
  DOCUMENT_LIBRARY_BRANDS,
  DOCUMENT_LIBRARY_LANGUAGES,
  DOCUMENT_LIBRARY_PRODUCT_TYPES,
  DOCUMENT_LIBRARY_TYPES
} from '@/features/foundation/document-library/types';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const documentLibrarySchema = z.object({
  code: z.string().min(1),
  name: z.string().min(1),
  documentType: z.enum(DOCUMENT_LIBRARY_TYPES),
  description: z.string().optional().nullable(),
  brand: z.enum(DOCUMENT_LIBRARY_BRANDS),
  language: z.enum(DOCUMENT_LIBRARY_LANGUAGES),
  productType: z.enum(DOCUMENT_LIBRARY_PRODUCT_TYPES),
  isActive: z.boolean().optional()
});

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentLibraryRead
    });

    const { searchParams } = request.nextUrl;
    const isActiveParam = searchParams.get('isActive');
    const items = await listDocumentLibraries(organization.id, {
      documentType:
        (searchParams.get('documentType') as (typeof DOCUMENT_LIBRARY_TYPES)[number] | null) ??
        undefined,
      brand:
        (searchParams.get('brand') as (typeof DOCUMENT_LIBRARY_BRANDS)[number] | null) ??
        undefined,
      language:
        (searchParams.get('language') as (typeof DOCUMENT_LIBRARY_LANGUAGES)[number] | null) ??
        undefined,
      productType:
        (searchParams.get('productType') as
          | (typeof DOCUMENT_LIBRARY_PRODUCT_TYPES)[number]
          | null) ?? undefined,
      isActive: isActiveParam === 'true' || isActiveParam === 'false' ? isActiveParam : undefined
    });

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

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentLibraryCreate
    });
    const payload = documentLibrarySchema.parse(await request.json());
    const library = await createDocumentLibrary({
      organizationId: organization.id,
      userId: session.user.id,
      values: payload
    });

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