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

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

  /**
   * API  list รายการจังหวัด
   *
   * @summary CRUD จังหวัด (ADMIN)
   *
   */
  @Get()
  async GetResult() {
    const _province = await this.provinceRepository.find({
      select: ["id", "name", "createdAt", "lastUpdatedAt", "createdFullName", "lastUpdateFullName"],
      order: { 
        name: "ASC",
        createdAt: "DESC" 
      },
    });
    return new HttpSuccess(_province);
  }

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

    return new HttpSuccess(_province);
  }

  /**
   * API สร้างรายการ body จังหวัด
   *
   * @summary CRUD จังหวัด (ADMIN)
   *
   */
  @Post()
  async Post(
    @Body()
    requestBody: CreateProvince,
    @Request() request: RequestWithUser,
  ) {
    const _province = Object.assign(new Province(), requestBody);
    if (!_province) {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลจังหวัดนี้");
    }

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

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

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

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