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

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

  /**
   * API  list รายการเพศ
   *
   * @summary ORG_058 - CRUD เพศ (ADMIN) #62
   *
   */
  @Get()
  async GetResult() {
    const _gender = await this.genderRepository.find({
      select: ["id", "name", "createdAt", "lastUpdatedAt", "createdFullName", "lastUpdateFullName"],
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(_gender);
  }

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

    return new HttpSuccess(_gender);
  }

  /**
   * API สร้างรายการ body เพศ
   *
   * @summary ORG_058 - CRUD เพศ (ADMIN) #62
   *
   */
  @Post()
  async Post(
    @Body()
    requestBody: CreateGender,
    @Request() request: RequestWithUser,
  ) {
    const _gender = Object.assign(new Gender(), requestBody);
    if (!_gender) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลเพศนี้");
    }

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

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

  /**
   * API  แก้ไขรายการ body เพศ
   *
   * @summary ORG_058 - CRUD เพศ (ADMIN) #62
   *
   * @param {string} id  Id เพศ
   */
  @Put("{id}")
  async Put(
    @Path() id: string,
    @Body()
    requestBody: UpdateGender,
    @Request() request: RequestWithUser,
  ) {
    const _gender = await this.genderRepository.findOne({ where: { id: id } });
    if (!_gender) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลเพศนี้");
    }
    const checkName = await this.genderRepository.findOne({
      where: { id: Not(id), name: requestBody.name },
    });
    if (checkName) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อนี้มีอยู่ในระบบแล้ว");
    }
    const before = structuredClone(_gender);
    _gender.lastUpdateUserId = request.user.sub;
    _gender.lastUpdateFullName = request.user.name;
    _gender.lastUpdatedAt = new Date();
    this.genderRepository.merge(_gender, requestBody);
    await this.genderRepository.save(_gender, { data: request });
    setLogDataDiff(request, { before, after: _gender });
    return new HttpSuccess();
  }

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