/**
 * Sync Schedule API (single schedule)
 * Manage individual sync schedules
 */

import { NextRequest, NextResponse } from 'next/server';
import { syncScheduler } from '@/lib/services/sync-scheduler';

/**
 * GET /api/sync/schedules/[id]
 * Get a specific schedule
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const schedule = await syncScheduler.getSchedule(id);
    
    if (!schedule) {
      return NextResponse.json(
        { error: 'Schedule not found' },
        { status: 404 }
      );
    }
    
    return NextResponse.json({
      success: true,
      schedule,
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error('[SCHEDULE API] Error fetching schedule:', errorMessage);
    
    return NextResponse.json(
      { error: 'Failed to fetch schedule', details: errorMessage },
      { status: 500 }
    );
  }
}

/**
 * PATCH /api/sync/schedules/[id]
 * Update a schedule
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    
    const schedule = await syncScheduler.updateSchedule(id, body);
    
    return NextResponse.json({
      success: true,
      schedule,
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error('[SCHEDULE API] Error updating schedule:', errorMessage);
    
    return NextResponse.json(
      { error: 'Failed to update schedule', details: errorMessage },
      { status: 500 }
    );
  }
}

/**
 * DELETE /api/sync/schedules/[id]
 * Delete a schedule
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    await syncScheduler.deleteSchedule(id);
    
    return NextResponse.json({
      success: true,
      message: 'Schedule deleted',
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error('[SCHEDULE API] Error deleting schedule:', errorMessage);
    
    return NextResponse.json(
      { error: 'Failed to delete schedule', details: errorMessage },
      { status: 500 }
    );
  }
}
