import { Controller, Get, Post, Patch, Delete, Body, Param, UseGuards } from "@nestjs/common";
import { CronService } from "./cron.service";
import { CreateCronDto, UpdateCronDto } from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
import { WorkspaceGuard } from "../common/guards";
import { Workspace, RequirePermission, Permission } from "../common/decorators";

/**
 * Controller for cron job scheduling endpoints
 * All endpoints require authentication and workspace context
 */
@Controller("cron")
@UseGuards(AuthGuard, WorkspaceGuard)
export class CronController {
  constructor(private readonly cronService: CronService) {}

  /**
   * POST /api/cron
   * Create a new cron schedule
   * Requires: MEMBER role or higher
   */
  @Post()
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async create(@Body() createCronDto: CreateCronDto, @Workspace() workspaceId: string) {
    return this.cronService.create(Object.assign({}, createCronDto, { workspaceId }));
  }

  /**
   * GET /api/cron
   * Get all cron schedules for workspace
   * Requires: Any workspace member
   */
  @Get()
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findAll(@Workspace() workspaceId: string) {
    return this.cronService.findAll(workspaceId);
  }

  /**
   * GET /api/cron/:id
   * Get a single cron schedule
   * Requires: Any workspace member
   */
  @Get(":id")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findOne(@Param("id") id: string, @Workspace() workspaceId: string) {
    return this.cronService.findOne(id, workspaceId);
  }

  /**
   * PATCH /api/cron/:id
   * Update a cron schedule
   * Requires: MEMBER role or higher
   */
  @Patch(":id")
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async update(
    @Param("id") id: string,
    @Body() updateCronDto: UpdateCronDto,
    @Workspace() workspaceId: string
  ) {
    return this.cronService.update(id, workspaceId, updateCronDto);
  }

  /**
   * DELETE /api/cron/:id
   * Delete a cron schedule
   * Requires: ADMIN role or higher
   */
  @Delete(":id")
  @RequirePermission(Permission.WORKSPACE_ADMIN)
  async remove(@Param("id") id: string, @Workspace() workspaceId: string) {
    return this.cronService.remove(id, workspaceId);
  }
}
