/**
 * Sync Schedules API
 * Manage scheduled automatic syncs
 */

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

/**
 * GET /api/sync/schedules
 * Get all sync schedules
 */
export async function GET() {
  try {
    const schedules = await syncScheduler.getSchedules();
    
    return NextResponse.json({
      success: true,
      schedules,
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error('[SCHEDULES API] Error fetching schedules:', errorMessage);
    
    return NextResponse.json(
      { error: 'Failed to fetch schedules', details: errorMessage },
      { status: 500 }
    );
  }
}

/**
 * POST /api/sync/schedules
 * Create a new schedule
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate required fields
    if (!body.id || !body.name || !body.cron_expression || !body.sync_type) {
      return NextResponse.json(
        { error: 'Missing required fields: id, name, cron_expression, sync_type' },
        { status: 400 }
      );
    }
    
    // Validate sync_type
    if (!['incremental', 'full'].includes(body.sync_type)) {
      return NextResponse.json(
        { error: 'Invalid sync_type. Must be "incremental" or "full"' },
        { status: 400 }
      );
    }
    
    const schedule = await syncScheduler.createSchedule({
      id: body.id,
      name: body.name,
      description: body.description || '',
      cron_expression: body.cron_expression,
      sync_type: body.sync_type,
      years_back: body.years_back,
      is_enabled: body.is_enabled ?? false,
    });
    
    return NextResponse.json({
      success: true,
      schedule,
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error('[SCHEDULES API] Error creating schedule:', errorMessage);
    
    return NextResponse.json(
      { error: 'Failed to create schedule', details: errorMessage },
      { status: 500 }
    );
  }
}
