// src/app/api/documents/route.ts

import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma';
// برای دریافت همه اسناد
export async function GET() {
  try {
    const generalDocument = await prisma.generalDocument.findMany()


    return NextResponse.json(generalDocument[0]?.document || [])
  } catch (error) {
    console.error('Error fetching documents:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch documents' },
      { status: 500 }
    )
  }
}

// برای وارد کردن از فایل JSON یا ذخیره‌سازی
export async function PUT(req: Request) {
  try {
    const document = await req.json()

    // حذف داده قبلی
    await prisma.generalDocument.deleteMany({})

    await prisma.generalDocument.create({
      data: {
        document: document
      }
    })

    return NextResponse.json({
      success: true,
      count: Array.isArray(document) ? document.length : 0,
      message: 'Document saved successfully'
    })
  } catch (error) {
    console.error('Error saving document:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to save document' },
      { status: 500 }
    )
  }
}

// این متد را می‌توان برای یکسان‌سازی با POST استفاده کرد
export async function POST(req: Request) {
  return PUT(req)
}