import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
} from "@nestjs/common";
import { ProjectsService } from "./projects.service";
import { CreateProjectDto, UpdateProjectDto, QueryProjectsDto } from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
import { WorkspaceGuard, PermissionGuard } from "../common/guards";
import { Workspace, Permission, RequirePermission } from "../common/decorators";
import { CurrentUser } from "../auth/decorators/current-user.decorator";
import type { AuthenticatedUser } from "../common/types/user.types";

@Controller("projects")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class ProjectsController {
  constructor(private readonly projectsService: ProjectsService) {}

  @Post()
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async create(
    @Body() createProjectDto: CreateProjectDto,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.projectsService.create(workspaceId, user.id, createProjectDto);
  }

  @Get()
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findAll(@Query() query: QueryProjectsDto, @Workspace() workspaceId: string) {
    return this.projectsService.findAll(Object.assign({}, query, { workspaceId }));
  }

  @Get(":id")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findOne(@Param("id") id: string, @Workspace() workspaceId: string) {
    return this.projectsService.findOne(id, workspaceId);
  }

  @Patch(":id")
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async update(
    @Param("id") id: string,
    @Body() updateProjectDto: UpdateProjectDto,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.projectsService.update(id, workspaceId, user.id, updateProjectDto);
  }

  @Delete(":id")
  @RequirePermission(Permission.WORKSPACE_ADMIN)
  async remove(
    @Param("id") id: string,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.projectsService.remove(id, workspaceId, user.id);
  }
}
