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 {
  pgCreateBackgroundJobLog,
  pgGetScheduleJobById,
  pgListBackgroundJobLogs,
  pgUpdateScheduleJob,
} from '@/lib/postgres/scheduler';

async function authorize() {
  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 { ok: false as const, response: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
  }

  return { ok: true as const, session };
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await authorize();
  if (!auth.ok) return auth.response;

  try {
    const { id } = await params;
    const { searchParams } = new URL(request.url);
    const logsLimit = Math.max(1, Math.min(500, Number(searchParams.get('logsLimit') || 100)));

    const job = await pgGetScheduleJobById(id);
    if (!job) {
      return NextResponse.json({ error: 'Job not found' }, { status: 404 });
    }

    const logs = await pgListBackgroundJobLogs({ jobId: id, limit: logsLimit });

    return NextResponse.json({ job, logs }, { status: 200 });
  } catch (error) {
    console.error('Error fetching scheduler job details:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await authorize();
  if (!auth.ok) return auth.response;

  try {
    const { id } = await params;
    const body = await request.json();
    const action = String(body?.action || '').trim() as 'pause' | 'resume' | 'retry' | 'cancel';

    if (!['pause', 'resume', 'retry', 'cancel'].includes(action)) {
      return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }

    const job = await pgGetScheduleJobById(id);
    if (!job) {
      return NextResponse.json({ error: 'Job not found' }, { status: 404 });
    }

    const actorId = String((auth.session.user as any)?.id || (auth.session.user as any)?.username || 'system');

    let updated = null;

    if (action === 'pause') {
      updated = await pgUpdateScheduleJob(id, { status: 'paused', updatedBy: actorId });
    } else if (action === 'resume') {
      updated = await pgUpdateScheduleJob(id, {
        status: 'active',
        nextRunDate: new Date().toISOString(),
        updatedBy: actorId,
      });
    } else if (action === 'cancel') {
      updated = await pgUpdateScheduleJob(id, { status: 'cancelled', updatedBy: actorId });
    } else {
      await pgCreateBackgroundJobLog({
        jobId: id,
        jobType: 'generate_document',
        status: 'retry',
        createdBy: actorId,
      });
      updated = await pgUpdateScheduleJob(id, {
        status: 'active',
        retryCount: 0,
        lastError: '',
        nextRunDate: new Date().toISOString(),
        updatedBy: actorId,
      });
    }

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

    return NextResponse.json({ item: updated }, { status: 200 });
  } catch (error) {
    console.error('Error updating scheduler job:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
