import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
} from "@nestjs/common";
import { DomainsService } from "./domains.service";
import { CreateDomainDto, UpdateDomainDto, QueryDomainsDto } 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("domains")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class DomainsController {
  constructor(private readonly domainsService: DomainsService) {}

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

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

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

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

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