import {
  Body,
  Controller,
  HttpCode,
  HttpStatus,
  Post,
  UseGuards,
} from '@nestjs/common';
import { AllowAuth } from '../common/decorators/allow-auth.decorator';
import { RequireScopes } from '../common/decorators/require-scopes.decorator';
import { ServiceCredentialGuard } from '../common/guards/service-credential/service-credential.guard';
import { DryRunBodyDto } from './dto/dry-run.dto';
import { ReconcileScheduledJobsDto } from './dto/reconcile-scheduled-jobs.dto';
import { RegisterScheduledJobBodyDto } from './dto/register-scheduled-job-body.dto';
import { RunIfDueBodyDto } from './dto/run-if-due-body.dto';
import { UnregisterScheduledJobDto } from './dto/unregister-scheduled-job.dto';
import { ScheduledJobsService } from './scheduled-jobs.service';

@Controller('scheduled-jobs')
export class ScheduledJobsController {
  constructor(private readonly scheduledJobsService: ScheduledJobsService) {}

  @Post('register')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:scheduled-jobs:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  register(@Body() body: RegisterScheduledJobBodyDto) {
    return this.scheduledJobsService.register(body.job);
  }

  @Post('unregister')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:scheduled-jobs:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  unregister(@Body() body: UnregisterScheduledJobDto) {
    return this.scheduledJobsService.unregister(body.jobId);
  }

  @Post('run-now')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:scheduled-jobs:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  runNow(@Body() body: UnregisterScheduledJobDto) {
    return this.scheduledJobsService.runNow(body.jobId);
  }

  @Post('run-if-due')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:scheduled-jobs:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  runIfDue(@Body() body: RunIfDueBodyDto) {
    return this.scheduledJobsService.runIfDue(body.job);
  }

  @Post('reconcile')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:scheduled-jobs:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  reconcile(@Body() body: ReconcileScheduledJobsDto) {
    return this.scheduledJobsService.reconcile(body.jobs);
  }

  @Post('dry-run')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:scheduled-jobs:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.OK)
  dryRun(@Body() body: DryRunBodyDto) {
    return this.scheduledJobsService.dryRun(body);
  }
}
