import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  getDocumentLibraryById,
  updateDocumentLibrary
} 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';

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

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

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

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

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentLibraryUpdate
    });
    const payload = updateDocumentLibrarySchema.parse(await request.json());
    const library = await updateDocumentLibrary({
      id,
      organizationId: organization.id,
      userId: session.user.id,
      values: payload
    });

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