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

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

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

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

    return new HttpSuccess(_district);
  }

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

    const chkProvince = await this.provinceRepository.findOne({
      where: { id: requestBody.provinceId },
    });
    if (!chkProvince) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลจังหวัดนี้");
    }

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

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

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

    const chkProvince = await this.provinceRepository.findOne({
      where: { id: requestBody.provinceId },
    });
    if (!chkProvince) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลจังหวัดนี้");
    }

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

  /**
   * API ลบรายการเขต
   *
   * @summary ORG_058 - CRUD เขต (ADMIN) #62
   *
   * @param {string} id  Id เขต
   */
  @Delete("{id}")
  async Delete(@Path() id: string) {
    // const _delDistrict = await this.districtRepository.findOne({
    //   where: { id: id },
    // });
    // if (!_delDistrict) {
    //   throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลเขตนี้");
    // }
    // await this.districtRepository.delete(_delDistrict.id);
    let result: any;
    try {
      result = await this.districtRepository.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();
  }
}
