import { Body, Controller, Delete, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { CurrentPrincipal } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
import { RequireScopes } from '../auth/decorators/scopes.decorator';
import { UserOrApiKeyGuard } from '../auth/guards/auth.guard';
import { OrgRolesGuard } from '../auth/guards/org-roles.guard';
import { ScopesGuard } from '../auth/guards/scopes.guard';
import { Principal } from '../auth/principal';
import { CreateJobDto, QueryJobsDto, UpdateJobDto } from './dto/jobs.dto';
import { JobsService } from './jobs.service';

@ApiTags('jobs')
@ApiBearerAuth('jwt')
@ApiSecurity('apiKey')
@Controller('orgs/:orgId/jobs')
@UseGuards(UserOrApiKeyGuard, OrgRolesGuard, ScopesGuard)
export class JobsController {
  constructor(private readonly jobsService: JobsService) {}

  @Get()
  @RequireScopes('jobs:read')
  list(@Param('orgId') orgId: string, @Query() query: QueryJobsDto) {
    return this.jobsService.list(orgId, query);
  }

  @Get(':jobId')
  @RequireScopes('jobs:read')
  get(@Param('orgId') orgId: string, @Param('jobId') jobId: string) {
    return this.jobsService.get(orgId, jobId);
  }

  @Post()
  @Roles('MEMBER')
  @RequireScopes('jobs:write')
  create(
    @Param('orgId') orgId: string,
    @Body() dto: CreateJobDto,
    @CurrentPrincipal() principal: Principal,
  ) {
    return this.jobsService.create(orgId, dto, principal.type === 'user' ? principal.userId : null);
  }

  @Patch(':jobId')
  @Roles('MEMBER')
  @RequireScopes('jobs:write')
  update(@Param('orgId') orgId: string, @Param('jobId') jobId: string, @Body() dto: UpdateJobDto) {
    return this.jobsService.update(orgId, jobId, dto);
  }

  @Delete(':jobId')
  @Roles('ORG_ADMIN')
  @RequireScopes('jobs:write')
  remove(@Param('orgId') orgId: string, @Param('jobId') jobId: string) {
    return this.jobsService.remove(orgId, jobId);
  }
}
