import {
  Controller,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Response,
  Get,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { CreateRank, Rank } from "../entities/Rank";
import { Not } from "typeorm";
import { setLogDataDiff } from "../interfaces/utils";
import { RequestWithUser } from "../middlewares/user";
@Route("api/v1/org/metadata/rank")
@Tags("Rank")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class RankController extends Controller {
  private rankRepository = AppDataSource.getRepository(Rank);

  /**
   * API สร้างยศ
   *
   * @summary ORG_059 - สร้างยศ (ADMIN) #65
   *
   */
  @Post()
  async createRank(
    @Body()
    requestBody: CreateRank,
    @Request() request: RequestWithUser,
  ) {
    const checkName = await this.rankRepository.findOne({
      where: { name: requestBody.name },
    });

    if (checkName) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อนี้มีอยู่ในระบบแล้ว");
    }

    const before = null;
    const rank = Object.assign(new Rank(), requestBody);
    rank.createdUserId = request.user.sub;
    rank.createdFullName = request.user.name;
    rank.lastUpdateUserId = request.user.sub;
    rank.lastUpdateFullName = request.user.name;
    rank.createdAt = new Date();
    rank.lastUpdatedAt = new Date();
    await this.rankRepository.save(rank, { data: request });
    setLogDataDiff(request, { before, after: rank });
    return new HttpSuccess();
  }

  /**
   * API แก้ไขยศ
   *
   * @summary ORG_059 - แก้ไขยศ (ADMIN) #65
   *
   * @param {string} id  Id ยศ
   */
  @Put("{id}")
  async updateRank(
    @Path() id: string,
    @Body()
    requestBody: CreateRank,
    @Request() request: RequestWithUser,
  ) {
    const rank = await this.rankRepository.findOne({ where: { id: id } });
    if (!rank) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
    }

    const checkName = await this.rankRepository.findOne({
      where: { id: Not(id), name: requestBody.name },
    });

    if (checkName) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อนี้มีอยู่ในระบบแล้ว");
    }
    const before = structuredClone(rank);
    rank.lastUpdateUserId = request.user.sub;
    rank.lastUpdateFullName = request.user.name;
    rank.lastUpdatedAt = new Date();
    this.rankRepository.merge(rank, requestBody);
    await this.rankRepository.save(rank, { data: request });
    setLogDataDiff(request, { before, after: rank });
    return new HttpSuccess();
  }

  /**
   * API ลบยศ
   *
   * @summary ORG_059 - ลบยศ (ADMIN) #65
   *
   * @param {string} id  Id ยศ
   */
  @Delete("{id}")
  async deleteRank(@Path() id: string, @Request() req: RequestWithUser) {
    const delRank = await this.rankRepository.findOne({
      where: { id },
    });
    if (!delRank) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
    }
    await this.rankRepository.remove(delRank, { data: req });
    return new HttpSuccess();
  }

  /**
   * API รายละเอียดรายการยศ
   *
   * @summary ORG_059 - รายละเอียดรายการยศ  (ADMIN) #65
   *
   * @param {string} id  Id ยศ
   */
  @Get("{id}")
  async detailRank(@Path() id: string) {
    const rank = await this.rankRepository.findOne({
      where: { id },
      select: ["id", "name"],
    });
    if (!rank) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(rank);
  }

  /**
   * API รายการยศ
   *
   * @summary ORG_059 - รายการยศ (ADMIN) #65
   *
   */
  @Get()
  async listRank() {
    const rank = await this.rankRepository.find({
      select: ["id", "name", "createdAt", "lastUpdatedAt", "createdFullName", "lastUpdateFullName"],
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(rank);
  }
}
