import type { Request as ExRequest } from "express";
import { Body, Controller, Get, Post, Query, Request, Response, Route, SuccessResponse, Tags } from "tsoa";
import { createProject, listProjects } from "../repository";
import type { CreateProjectRequest, ErrorResponse, ProjectEnvelope, ProjectsEnvelope } from "../models";
import { HttpError } from "../httpErrors";
import { getDatabase, normalizeCreateProject } from "./shared";

@Route("projects")
@Tags("Projects")
export class ProjectsController extends Controller {
  @Get()
  public listProjects(
    @Request() request: ExRequest,
    @Query() orgId?: string,
  ): ProjectsEnvelope {
    return { projects: listProjects(getDatabase(request), orgId) };
  }

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

    return { project };
  }
}
