import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { pgGetSettings } from '@/lib/postgres/data-access';
import { pgGetSchedulerStatus, pgUpdateSchedulerStatus } from '@/lib/postgres/scheduler';

export async function POST(request: NextRequest) {
  const session = await getSession();
  const settings = await pgGetSettings();

  if (
    !session?.user ||
    (!hasEmployeePermission(session.user, settings, 'admin.accounting') &&
      !hasEmployeePermission(session.user, settings, 'admin.expense-recurring'))
  ) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { enable = true } = body;

    const currentStatus = await pgGetSchedulerStatus();
    if (!currentStatus) {
      return NextResponse.json(
        { error: 'Scheduler status not found' },
        { status: 404 }
      );
    }

    // Update scheduler status
    const updatedStatus = await pgUpdateSchedulerStatus({
      isRunning: enable,
      lastCheckAt: new Date().toISOString(),
      nextCheckAt: enable 
        ? new Date(Date.now() + (currentStatus.checkIntervalSeconds * 1000)).toISOString()
        : undefined,
      isHealthy: enable ? true : currentStatus.isHealthy,
    });

    if (!updatedStatus) {
      return NextResponse.json(
        { error: 'Failed to update scheduler status' },
        { status: 500 }
      );
    }

    return NextResponse.json(
      {
        success: true,
        message: enable ? 'Scheduler started' : 'Scheduler stopped',
        status: updatedStatus,
      },
      { status: 200 }
    );
  } catch (error) {
    console.error('Error starting scheduler:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
