import {
  Controller,
  Post,
  Put,
  Delete,
  Route,
  Security,
  Tags,
  Body,
  Path,
  Request,
  Response,
  Get,
  Example,
} from "tsoa";
import { Not } from "typeorm";
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 { CreatePosExecutive, PosExecutive } from "../entities/PosExecutive";
import { Position } from "../entities/Position";
import { RequestWithUser } from "../middlewares/user";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/pos/executive")
@Tags("PosExecutive")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class PosExecutiveController extends Controller {
  private posExecutiveRepository = AppDataSource.getRepository(PosExecutive);
  private positionRepository = AppDataSource.getRepository(Position);

  /**
   * API เพิ่มตำแหน่งทางการบริหาร
   *
   * @summary ORG_041 - เพิ่มตำแหน่งทางการบริหาร (ADMIN) #44
   *
   */
  @Post()
  async createPosExecutive(
    @Body()
    requestBody: CreatePosExecutive,
    @Request() request: RequestWithUser,
  ) {
    const checkName = await this.posExecutiveRepository.findOne({
      where: { posExecutiveName: requestBody.posExecutiveName },
    });

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

    const posExecutive = Object.assign(new PosExecutive(), requestBody);
    if (requestBody.posExecutivePriority == null) {
      const checkPriority = await this.posExecutiveRepository.findOne({
        order: { posExecutivePriority: "DESC" },
      });
      if (checkPriority == null) {
        posExecutive.posExecutivePriority = 1;
      } else {
        posExecutive.posExecutivePriority = checkPriority.posExecutivePriority + 1;
      }
    } else {
      posExecutive.posExecutivePriority = requestBody.posExecutivePriority;
    }
    const _checkPriority = await this.posExecutiveRepository.findOne({
      where: {
        posExecutivePriority: posExecutive.posExecutivePriority,
      },
    });

    if (_checkPriority) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ลำดับนี้มีอยู่ในระบบแล้ว");
    }
    const before = null;
    posExecutive.createdUserId = request.user.sub;
    posExecutive.createdFullName = request.user.name;
    posExecutive.lastUpdateUserId = request.user.sub;
    posExecutive.lastUpdateFullName = request.user.name;
    posExecutive.createdAt = new Date();
    posExecutive.lastUpdatedAt = new Date();
    await this.posExecutiveRepository.save(posExecutive, { data: request });
    setLogDataDiff(request, { before, after: posExecutive });
    return new HttpSuccess(posExecutive.id);
  }

  /**
   * API แก้ไขตำแหน่งทางการบริหาร
   *
   * @summary ORG_042 - แก้ไขตำแหน่งทางการบริหาร (ADMIN) #45
   *
   * @param {string} id  Id ตำแหน่งทางการบริหาร
   */
  @Put("{id}")
  async updatePosExecutive(
    @Path() id: string,
    @Body()
    requestBody: CreatePosExecutive,
    @Request() request: RequestWithUser,
  ) {
    const posExecutive = await this.posExecutiveRepository.findOne({ where: { id: id } });
    if (!posExecutive) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งทางการบริหารนี้");
    }

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

    if (checkName) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อนี้มีอยู่ในระบบแล้ว");
    }
    if (requestBody.posExecutivePriority == null) {
      const checkPriority = await this.posExecutiveRepository.findOne({
        order: { posExecutivePriority: "DESC" },
      });
      if (checkPriority == null) {
        posExecutive.posExecutivePriority = 1;
      } else {
        posExecutive.posExecutivePriority = checkPriority.posExecutivePriority + 1;
      }
    } else {
      posExecutive.posExecutivePriority = requestBody.posExecutivePriority;
    }
    const _checkPriority = await this.posExecutiveRepository.findOne({
      where: {
        id: Not(id),
        posExecutivePriority: posExecutive.posExecutivePriority,
      },
    });

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

  /**
   * API ลบอัตรากำลัง
   *
   * @summary ORG_043 - ลบตำแหน่งทางการบริหาร (ADMIN) #46
   *
   * @param {string} id  Id ตำแหน่งทางการบริหาร
   */
  @Delete("{id}")
  async deletePosExecutive(@Path() id: string) {
    const delPosExecutive = await this.posExecutiveRepository.findOne({
      where: { id },
    });
    if (!delPosExecutive) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งทางการบริหารนี้");
    }
    await this.positionRepository.delete({ posExecutiveId: id });
    await this.posExecutiveRepository.delete({ id });
    return new HttpSuccess();
  }

  /**
   * API รายละเอียดตำแหน่งทางการบริหาร
   *
   * @summary ORG_044 - รายละเอียดตำแหน่งทางการบริหาร (ADMIN) #47
   *
   * @param {string} id  Id ตำแหน่งทางการบริหาร
   */
  @Get("{id}")
  async detailPosExecutive(@Path() id: string) {
    const posExecutive = await this.posExecutiveRepository.findOne({
      where: { id },
      select: ["id", "posExecutiveName", "posExecutivePriority"],
    });
    if (!posExecutive) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(posExecutive);
  }

  /**
   * API รายการตำแหน่งทางการบริหาร
   *
   * @summary ORG_026 - รายการตำแหน่งทางการบริหาร (ADMIN) #28
   *
   */
  @Get()
  @Example([
    {
      id: "00000000-0000-0000-0000-000000000000",
      posExecutiveName: "นักบริหาร",
      posExecutivePriority: 1,
    },
  ])
  async GetPosExecutive() {
    const posExecutive = await this.posExecutiveRepository.find({
      select: ["id", "posExecutiveName", "posExecutivePriority", "createdAt", "lastUpdatedAt", "lastUpdateFullName"],
      order: { 
        posExecutivePriority: "ASC",
        createdAt: "DESC"
      },
    });
    return new HttpSuccess(posExecutive);
  }
}
