import {
  Body,
  Controller,
  Delete,
  HttpCode,
  NotFoundException,
  Param,
  Post,
  Put,
  Req,
  UseGuards,
} from "@nestjs/common";
import type { Request } from "express";
import { JwtAuthGuard } from "../auth/jwt-auth.guard.js";
import { CreateFunctionDto, UpdateFunctionDto } from "@sigma/common";
import type { FunctionDocument } from "../schemas/function.schema.js";
import { ProjectFunctionsService } from "../services/project-functions.service.js";

@Controller("projects/:projectId/functions")
export class FunctionsController {
  constructor(
    private readonly projectFunctionsService: ProjectFunctionsService
  ) {}

  @UseGuards(JwtAuthGuard)
  @Post()
  create(
    @Req() request: Request,
    @Param("projectId") projectId: string,
    @Body() payload: CreateFunctionDto
  ): Promise<FunctionDocument> {
    return this.projectFunctionsService.create(
      request.user.userId,
      projectId,
      payload
    );
  }

  @UseGuards(JwtAuthGuard)
  @Put(":functionId")
  async update(
    @Req() request: Request,
    @Param("projectId") projectId: string,
    @Param("functionId") functionId: string,
    @Body() payload: UpdateFunctionDto
  ): Promise<FunctionDocument> {
    const func = await this.projectFunctionsService.update(
      request.user.userId,
      projectId,
      functionId,
      payload
    );

    if (!func) {
      throw new NotFoundException("Function not found");
    }

    return func;
  }

  @UseGuards(JwtAuthGuard)
  @Delete(":functionId")
  @HttpCode(204)
  async delete(
    @Req() request: Request,
    @Param("projectId") projectId: string,
    @Param("functionId") functionId: string
  ): Promise<FunctionDocument | null> {
    const func = await this.projectFunctionsService.delete(
      request.user.userId,
      projectId,
      functionId
    );

    if (!func) {
      throw new NotFoundException("Function not found");
    }

    return func;
  }
}
