import { CurrentUser } from "@edr/api-common";
import {
  NotificationAudience,
  NotificationPriority,
  NotificationType,
} from "@edr/types";
import {
  Body,
  Controller,
  Get,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
  Query,
  UseGuards,
} from "@nestjs/common";
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
import { JwtGuard } from "@tria-plc/api-common/modules/auth/services/jwt.guard";

import {
  AuthUserPayload,
  resolveAuthUserId,
} from "../../common/resolve-auth-user-id";
import { ListNotificationsQueryDto } from "./dto/list-notifications-query.dto";
import { NotificationInboxService } from "./notification-inbox.service";

@ApiTags("notifications")
@ApiBearerAuth()
@UseGuards(JwtGuard)
@Controller("notifications")
export class NotificationInboxController {
  constructor(private readonly service: NotificationInboxService) {}

  @Get()
  @ApiOperation({ summary: "List my notifications (paginated, newest first)" })
  list(
    @CurrentUser() user: AuthUserPayload,
    @Query() query: ListNotificationsQueryDto,
  ) {
    return this.service.list(resolveAuthUserId(user), query);
  }

  @Get("unread-count")
  @ApiOperation({ summary: "Count my unread notifications" })
  unreadCount(@CurrentUser() user: AuthUserPayload) {
    return this.service.unreadCount(resolveAuthUserId(user));
  }

  @Patch(":id/read")
  @ApiOperation({ summary: "Mark one of my notifications as read" })
  markRead(
    @CurrentUser() user: AuthUserPayload,
    @Param("id", ParseUUIDPipe) id: string,
  ) {
    return this.service.markRead(id, resolveAuthUserId(user));
  }

  @Post("read-all")
  @ApiOperation({ summary: "Mark all my notifications as read" })
  markAllRead(@CurrentUser() user: AuthUserPayload) {
    return this.service.markAllRead(resolveAuthUserId(user));
  }

  // TODO: remove before merge — dev/verification helper only.
  @Post("test")
  @ApiOperation({
    summary: "[dev] Send a test notification to the current user",
  })
  sendTest(
    @CurrentUser() user: AuthUserPayload,
    @Body()
    body: {
      audience?: NotificationAudience;
      type?: NotificationType;
      priority?: NotificationPriority;
      title?: string;
      message?: string;
    },
  ) {
    return this.service.sendTestToUser(resolveAuthUserId(user), body ?? {});
  }
}
