/**
 * Auto-generated by ${VOCAB.factory}
 * Task API Routes
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';

export const dynamic = 'force-dynamic';


// GET - List all Task records
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const skip = (page - 1) * limit;

    const [items, total] = await Promise.all([
      prisma.task.findMany({
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.task.count(),
    ]);

    return NextResponse.json({
      data: items,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Error fetching Task:', error);
    return NextResponse.json(
      { error: 'Failed to fetch Task records' },
      { status: 500 }
    );
  }
}


// POST - Create a new Task
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate required fields
    const required = ['type'];
    const missing = required.filter(field => !(field in body));
    if (missing.length > 0) {
      return NextResponse.json(
        { error: `Missing required fields: ${missing.join(', ')}` },
        { status: 400 }
      );
    }

    const task = await prisma.task.create({
      data: body,
    });

    return NextResponse.json(task, { status: 201 });
  } catch (error) {
    console.error('Error creating Task:', error);
    return NextResponse.json(
      { error: 'Failed to create Task' },
      { status: 500 }
    );
  }
}
