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 { 
  pgListActiveScheduleJobs,
  pgCreateBackgroundJobLog,
  pgUpdateSchedulerStatus,
  pgGetSchedulerStatus,
} from '@/lib/postgres/scheduler';
import type { SchedulerGenerateAllResponse } from '@/lib/types';

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 });
  }

  const startTime = Date.now();

  try {
    const body = await request.json().catch(() => ({}));
    // const { asOfDate, templateIds, contractIds, forceGenerate } = body;

    // Get active schedule jobs that are due
    const activeJobs = await pgListActiveScheduleJobs();

    if (activeJobs.length === 0) {
      return NextResponse.json<SchedulerGenerateAllResponse>(
        {
          success: true,
          jobsCreated: 0,
          jobsEnqueued: 0,
          failedJobs: 0,
          generatedDocuments: 0,
          processingTimeMs: Date.now() - startTime,
        },
        { status: 200 }
      );
    }

    // Create job logs for each active job
    const jobLogs = [];
    let failedCount = 0;

    for (const job of activeJobs) {
      try {
        const jobLog = await pgCreateBackgroundJobLog({
          jobId: job.id,
          jobType: 'generate_document',
          status: 'pending',
          createdBy: 'system',
        });

        if (jobLog) {
          jobLogs.push(jobLog);
        } else {
          failedCount++;
        }
      } catch (err) {
        console.error(`Failed to create job log for job ${job.id}:`, err);
        failedCount++;
      }
    }

    // Update scheduler status
    const currentStatus = await pgGetSchedulerStatus();
    if (currentStatus) {
      await pgUpdateSchedulerStatus({
        lastRunAt: new Date().toISOString(),
        totalJobs: activeJobs.length,
        activeJobs: activeJobs.length,
      });
    }

    const response: SchedulerGenerateAllResponse = {
      success: true,
      jobsCreated: jobLogs.length,
      jobsEnqueued: jobLogs.length,
      failedJobs: failedCount,
      generatedDocuments: 0, // Would be populated by actual generation service
      processingTimeMs: Date.now() - startTime,
    };

    if (failedCount > 0) {
      response.errors = [`${failedCount} jobs failed to enqueue`];
    }

    return NextResponse.json(response, { status: 200 });
  } catch (error) {
    console.error('Error generating all documents:', error);

    const response: SchedulerGenerateAllResponse = {
      success: false,
      jobsCreated: 0,
      jobsEnqueued: 0,
      failedJobs: 0,
      generatedDocuments: 0,
      processingTimeMs: Date.now() - startTime,
      errors: [error instanceof Error ? error.message : 'Internal Server Error'],
    };

    return NextResponse.json(response, { status: 500 });
  }
}
