import { Controller, ForbiddenException, Get, Param, UnauthorizedException } from "@nestjs/common";
import { Req } from "@nestjs/common";
import jwt from "jsonwebtoken";
import { checkWorkspaceMembership } from "@slackwsh/messaging";
import { PresenceService } from "./presence.service";

/**
 * HTTP snapshot endpoint — a client opening a workspace needs to know who's
 * currently online *before* any `presence:changed` event has fired (that
 * event only fires on the next state transition). Socket events keep it
 * live after that; this is just the initial hydration read.
 */
@Controller("workspaces/:workspaceId/presence")
export class PresenceController {
  constructor(private readonly presence: PresenceService) {}

  @Get()
  async get(@Req() req: any, @Param("workspaceId") workspaceId: string) {
    const header = req.headers?.authorization as string | undefined;
    if (!header?.startsWith("Bearer ")) throw new UnauthorizedException("missing bearer token");
    const secret = process.env.JWT_ACCESS_SECRET;
    if (!secret) throw new Error("JWT_ACCESS_SECRET is not set");
    let userId: string;
    try {
      userId = (jwt.verify(header.slice("Bearer ".length), secret) as { sub: string }).sub;
    } catch {
      throw new UnauthorizedException("invalid or expired access token");
    }

    if (!(await checkWorkspaceMembership(workspaceId, userId))) {
      throw new ForbiddenException("not a member of this workspace");
    }

    return { presence: await this.presence.getWorkspacePresence(workspaceId) };
  }
}
