import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AtlasProxyService } from '../atlas-proxy/atlas-proxy.service';

export interface RunBundle {
  jobId: string;
  versionId: string | null;
  code: string;
  env: Record<string, string>;
  fetchAllowlist: string[];
  credential?: { keyRef: string } | null;
  limits: { timeoutMs: number; memoryMb: number };
  overlapPolicy: 'SKIP' | 'QUEUE' | 'ALLOW';
  maxRetries: number;
  input: unknown;
}

export interface CreateRunInput {
  jobId: string;
  trigger: 'SCHEDULE' | 'MANUAL' | 'CATCHUP';
  scheduledFor?: string | null;
  attempt?: number;
}

export interface ReportRunInput {
  runId: string;
  jobId: string;
  status:
    | 'RUNNING'
    | 'SUCCESS'
    | 'FAILED'
    | 'TIMED_OUT'
    | 'SKIPPED'
    | 'CANCELLED';
  versionId?: string | null;
  attempt?: number;
  startedAt?: string | null;
  finishedAt?: string | null;
  durationMs?: number | null;
  output?: unknown;
  logs?: string | null;
  errorCode?: string | null;
  errorMessage?: string | null;
  errorStack?: string | null;
}

@Injectable()
export class ScheduledJobsRuntimeClient {
  private readonly basePath: string;

  constructor(
    private readonly atlasProxy: AtlasProxyService,
    configService: ConfigService,
  ) {
    this.basePath =
      configService.get<string>('ATLAS_SJOB_RUNTIME_CALLBACK_PATH') ||
      '/api/atlas/internal/scheduled-jobs-runtime';
  }

  getBundle(jobId: string): Promise<RunBundle> {
    return this.atlasProxy.forwardRequest<RunBundle>(
      'GET',
      `${this.basePath}/bundle/${jobId}`,
    );
  }

  async createRun(input: CreateRunInput): Promise<{ runId: string }> {
    const response = await this.atlasProxy.forwardRequest<{
      run: { runId: string };
    }>('POST', `${this.basePath}/runs`, { create: input });
    return response.run;
  }

  async reportRun(input: ReportRunInput): Promise<void> {
    await this.atlasProxy.forwardRequest<unknown>(
      'POST',
      `${this.basePath}/runs`,
      { report: input },
    );
  }
}
