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 { CreateRelationship, Relationship } from "../entities/Relationship";
import { Not } from "typeorm";
import { RequestWithUser } from "../middlewares/user";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/metadata/relationship")
@Tags("Relationship")
@Security("bearerAuth")
@Response(
  HttpStatusCode.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class RelationshipController extends Controller {
  private relationshipRepository = AppDataSource.getRepository(Relationship);

  /**
   * API สร้างสถานภาพ
   *
   * @summary ORG_060 - สร้างสถานภาพ (ADMIN) #65
   *
   */
  @Post()
  async createRelationship(
    @Body()
    requestBody: CreateRelationship,
    @Request() request: RequestWithUser,
  ) {
    const checkName = await this.relationshipRepository.findOne({
      where: { name: requestBody.name },
    });

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

  /**
   * API แก้ไขสถานภาพ
   *
   * @summary ORG_060 - แก้ไขสถานภาพ (ADMIN) #65
   *
   * @param {string} id  Id สถานภาพ
   */
  @Put("{id}")
  async updateRelationship(
    @Path() id: string,
    @Body()
    requestBody: CreateRelationship,
    @Request() request: RequestWithUser,
  ) {
    const relationship = await this.relationshipRepository.findOne({ where: { id: id } });
    if (!relationship) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลสถานภาพนี้");
    }

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

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

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

  /**
   * API ลบสถานภาพ
   *
   * @summary ORG_060 - ลบสถานภาพ (ADMIN) #65
   *
   * @param {string} id  Id สถานภาพ
   */
  @Delete("{id}")
  async deleteRelationship(@Path() id: string, @Request() request: RequestWithUser) {
    const delRelationship = await this.relationshipRepository.findOne({
      where: { id },
    });
    if (!delRelationship) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลสถานภาพนี้");
    }
    await this.relationshipRepository.remove(delRelationship, { data: request });
    return new HttpSuccess();
  }

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

  /**
   * API รายการสถานภาพ
   *
   * @summary ORG_060 - รายการสถานภาพ (ADMIN) #65
   *
   */
  @Get()
  async listRelationship() {
    const relationship = await this.relationshipRepository.find({
      select: ["id", "name", "createdAt", "lastUpdatedAt", "createdFullName", "lastUpdateFullName"],
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(relationship);
  }
}
