import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
} from "@nestjs/common";
import { EventsService } from "./events.service";
import { CreateEventDto, UpdateEventDto, QueryEventsDto } 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 for event endpoints
 * All endpoints require authentication and workspace context
 *
 * Guards are applied in order:
 * 1. AuthGuard - Verifies user authentication
 * 2. WorkspaceGuard - Validates workspace access and sets RLS context
 * 3. PermissionGuard - Checks role-based permissions
 */
@Controller("events")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class EventsController {
  constructor(private readonly eventsService: EventsService) {}

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

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

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

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

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