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 { Prefixe, CreatePrefixe, UpdatePrefixe } from "../entities/Prefixe";
import { Not } from "typeorm";
import { setLogDataDiff } from "../interfaces/utils";
import { RequestWithUser } from "../middlewares/user";

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

  /**
   * API  list รายการคำนำหน้า
   *
   * @summary ORG_056 - CRUD คำนำหน้า (ADMIN) #61
   *
   */
  @Get()
  async Get() {
    const _prefix = await this.prefixRepository.find({
      select: ["id", "name", "createdAt", "lastUpdatedAt", "createdFullName", "lastUpdateFullName"],
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(_prefix);
  }

  /**
   * API รายละเอียดรายการคำนำหน้า
   *
   * @summary ORG_056 - CRUD คำนำหน้า (ADMIN) #61
   *
   * @param {string} id  Id  คำนำหน้า
   */
  @Get("{id}")
  async GetById(@Path() id: string) {
    const _prefix = await this.prefixRepository.findOne({
      where: { id },
      select: ["id", "name"],
    });
    if (!_prefix) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(_prefix);
  }

  /**
   * API สร้างรายการ body คำนำหน้า
   *
   * @summary ORG_056 - CRUD คำนำหน้า (ADMIN) #61
   *
   */
  @Post()
  async Post(
    @Body()
    requestBody: CreatePrefixe,
    @Request() request: RequestWithUser,
  ) {
    const _prefix = Object.assign(new Prefixe(), requestBody);
    if (!_prefix) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }

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

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

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

  /**
   * API  แก้ไขรายการ body คำนำหน้า
   *
   * @summary ORG_056 - CRUD คำนำหน้า (ADMIN) #61
   *
   * @param {string} id  Id คำนำหน้า
   */
  @Put("{id}")
  async Put(
    @Path() id: string,
    @Body()
    requestBody: UpdatePrefixe,
    @Request() request: RequestWithUser,
  ) {
    const _prefix = await this.prefixRepository.findOne({ where: { id: id } });
    if (!_prefix) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำนำหน้าชื่อนี้");
    }
    const checkName = await this.prefixRepository.findOne({
      where: { id: Not(id), name: requestBody.name },
    });
    if (checkName) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อนี้มีอยู่ในระบบแล้ว");
    }

    const before = structuredClone(_prefix);
    _prefix.lastUpdateUserId = request.user.sub;
    _prefix.lastUpdateFullName = request.user.name;
    _prefix.lastUpdatedAt = new Date();
    this.prefixRepository.merge(_prefix, requestBody);
    await this.prefixRepository.save(_prefix, { data: request });
    setLogDataDiff(request, { before, after: _prefix });
    return new HttpSuccess();
  }

  /**
   * API ลบรายการคำนำหน้า
   *
   * @summary ORG_056 - CRUD คำนำหน้า (ADMIN) #61
   *
   * @param {string} id  Id คำนำหน้า
   */
  @Delete("{id}")
  async Delete(@Path() id: string, @Request() request: RequestWithUser) {
    const _delPrefix = await this.prefixRepository.findOne({
      where: { id: id },
    });
    if (!_delPrefix) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำนำหน้าชื่อนี้");
    }
    await this.prefixRepository.remove(_delPrefix, { data: request });
    return new HttpSuccess();
  }
}
