import type { Request as ExRequest } from "express";
import { Body, Controller, Get, Post, Query, Request, Response, Route, SuccessResponse, Tags } from "tsoa";
import { createUser, listUsers } from "../repository";
import type { CreateUserRequest, ErrorResponse, UserEnvelope, UsersEnvelope } from "../models";
import { HttpError } from "../httpErrors";
import { getDatabase, normalizeCreateUser } from "./shared";

@Route("users")
@Tags("Users")
export class UsersController extends Controller {
  @Get()
  public listUsers(
    @Request() request: ExRequest,
    @Query() orgId?: string,
  ): UsersEnvelope {
    return { users: listUsers(getDatabase(request), orgId) };
  }

  @Post()
  @SuccessResponse("201", "Created")
  @Response<ErrorResponse>(400, "Invalid payload")
  public createUser(
    @Request() request: ExRequest,
    @Body() body: CreateUserRequest,
  ): UserEnvelope {
    this.setStatus(201);
    const user = createUser(getDatabase(request), normalizeCreateUser(body));
    if (!user) {
      throw new HttpError(500, "Failed to create user.");
    }

    return { user };
  }
}
