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 { SubDistrict, CreateSubDistrict, UpdateSubDistrict } from "../entities/SubDistrict";
import { District } from "../entities/District";
import { Not } from "typeorm";
import { RequestWithUser } from "../middlewares/user";
import { setLogDataDiff } from "../interfaces/utils";

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

  /**
   * API  list รายการแขวง
   *
   * @summary ORG_058 - CRUD แขวง (ADMIN) #62
   *
   */
  @Get()
  async GetResult() {
    const _subDistrict = await this.subDistrictRepository.find({
      select: ["id", "name", "createdAt", "lastUpdatedAt", "createdFullName", "lastUpdateFullName"],
      order: { 
        name: "ASC",
        createdAt: "DESC"
      },
    });
    return new HttpSuccess(_subDistrict);
  }

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

    return new HttpSuccess(_subDistrict);
  }

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

    const chkDistrict = await this.districtRepository.findOne({
      where: { id: requestBody.districtId },
    });
    if (!chkDistrict) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลเขตนี้");
    }

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

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

  /**
   * API  แก้ไขรายการ body แขวง
   *
   * @summary ORG_058 - CRUD แขวง (ADMIN) #62
   *
   * @param {string} id  Id แขวง
   */
  @Put("{id}")
  async Put(
    @Path() id: string,
    @Body()
    requestBody: UpdateSubDistrict,
    @Request() request: RequestWithUser,
  ) {
    const _subDistrict = await this.subDistrictRepository.findOne({ where: { id: id } });
    if (!_subDistrict) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแขวงนี้");
    }

    const chkDistrict = await this.districtRepository.findOne({
      where: { id: requestBody.districtId },
    });
    if (!chkDistrict) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลเขตนี้");
    }

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

  /**
   * API ลบรายการแขวง
   *
   * @summary ORG_058 - CRUD แขวง (ADMIN) #62
   *
   * @param {string} id  Id แขวง
   */
  @Delete("{id}")
  async Delete(@Path() id: string) {
    // const _delSubDistrict = await this.subDistrictRepository.findOne({
    //   where: { id: id },
    // });
    // if (!_delSubDistrict) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแขวงนี้");
    // }
    // await this.subDistrictRepository.delete(_delSubDistrict.id);
    let result: any;
    try {
      result = await this.subDistrictRepository.delete({ id: id });
    } catch {
      throw new HttpError(
        HttpStatusCode.NOT_FOUND,
        "ไม่สามารถลบได้เนื่องจากมีการใช้งานข้อมูลแขวง/ตำบลนี้อยู่",
      );
    }
    if (result.affected == undefined || result.affected <= 0) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess();
  }
}
