import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Response,
} from "tsoa";
import HttpStatusCode from "../interfaces/http-status";
import { AppDataSource } from "../database/data-source";
import { Issues, CreateIssueRequest, UpdateIssueRequest } from "../entities/Issues";
import HttpSuccess from "../interfaces/http-success";
import { RequestWithUser } from "../middlewares/user";

@Route("api/v1/org/issues")
@Tags("issues")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class IssuesController extends Controller {
  private issuesRepository = AppDataSource.getRepository(Issues);

  @Get("lists")
  async getIssues() {
    const issues = await this.issuesRepository.find({
      order: {
        createdAt: "DESC",
      },
    });
    return new HttpSuccess(issues);
  }

  @Post("")
  async createIssue(@Body() requestBody: CreateIssueRequest, @Request() request: RequestWithUser) {
    let issue = this.issuesRepository.create(requestBody);
    issue.createdUserId = request.user.sub;
    issue.createdFullName = request.user.name;
    issue.createdAt = new Date();
    issue.lastUpdateUserId = "";
    issue.lastUpdateFullName = "";
    await this.issuesRepository.save(issue);

    return new HttpSuccess(issue);
  }

  @Put("{id}")
  async updateIssue(
    @Path("id") id: string,
    @Body() requestBody: Partial<UpdateIssueRequest>,
    @Request() request: RequestWithUser,
  ) {
    let issue = await this.issuesRepository.findOneBy({ id });
    if (!issue) {
      this.setStatus(HttpStatusCode.NOT_FOUND);
      return { message: "ไม่พบข้อมูลที่ต้องการแก้ไข" };
    }
    Object.assign(issue, requestBody);
    issue.lastUpdateUserId = request.user.sub;
    issue.lastUpdateFullName = request.user.name;
    issue.lastUpdatedAt = new Date();
    await this.issuesRepository.save(issue);
    return new HttpSuccess(issue);
  }
}
