import { Controller, Route, Security, Tags, Body, Path, Request, Get, Patch } from "tsoa";

import HttpSuccess from "../interfaces/http-success";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import { RequestWithUser } from "../middlewares/user";
import { ProfileAddressHistory } from "../entities/Profile";
import { AppDataSource } from "../database/data-source";
import { ProfileEmployee, UpdateProfileAddressEmployee } from "../entities/ProfileEmployee";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile-temp/address")
@Tags("ProfileAddressEmployee")
@Security("bearerAuth")
export class ProfileAddressEmployeeTempController extends Controller {
  private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee);
  private profileAddressHistoryRepo = AppDataSource.getRepository(ProfileAddressHistory);

  @Get("user")
  public async detailProfileAddressUser(@Request() request: { user: Record<string, any> }) {
    const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const getProfileAddress = await this.profileEmployeeRepo.findOne({
      where: { id: profile.id },
      select: [
        "id",
        "registrationAddress",
        "registrationProvinceId",
        "registrationDistrictId",
        "registrationSubDistrictId",
        "registrationZipCode",
        "currentAddress",
        "currentProvinceId",
        "currentDistrictId",
        "currentSubDistrictId",
        "currentZipCode",
      ],
      order: { createdAt: "ASC" },
    });
    if (!getProfileAddress) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getProfileAddress);
  }

  /**
   *
   * @summary ข้อมูลที่อยู่
   *
   */
  @Get("{profileEmployeeId}")
  public async detailProfileAddress(
    @Path() profileEmployeeId: string,
    @Request() req: RequestWithUser,
  ) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_TEMP");
    if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP");
    const getProfileAddress = await this.profileEmployeeRepo.findOne({
      where: { id: profileEmployeeId },
      select: [
        "id",
        "registrationAddress",
        "registrationProvinceId",
        "registrationDistrictId",
        "registrationSubDistrictId",
        "registrationZipCode",
        "currentAddress",
        "currentProvinceId",
        "currentDistrictId",
        "currentSubDistrictId",
        "currentZipCode",
      ],
    });
    if (!getProfileAddress) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getProfileAddress);
  }

  /**
   *
   * @summary ประวัติแก้ไขที่อยู่ by keycloak
   *
   */
  @Get("history/user")
  public async getProfileAddressHistoryUser(@Request() request: RequestWithUser) {
    const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const record = await this.profileAddressHistoryRepo.find({
      where: { profileEmployeeId: profile.id },
      relations: [
        "registrationProvince",
        "registrationDistrict",
        "registrationSubDistrict",
        "currentProvince",
        "currentDistrict",
        "currentSubDistrict",
      ],
      order: { createdAt: "DESC" },
    });
    const _record = record.map((item) => ({
      id: item.id,
      currentAddress: item.currentAddress,
      registrationAddress: item.registrationAddress,
      currentZipCode: item.currentZipCode,
      registrationZipCode: item.registrationZipCode,
      currentProvince: item.currentProvince?.name ?? null,
      registrationProvince: item.registrationProvince?.name ?? null,
      currentDistrict: item.currentDistrict?.name ?? null,
      registrationDistrict: item.registrationDistrict?.name ?? null,
      currentSubDistrict: item.currentSubDistrict?.name ?? null,
      registrationSubDistrict: item.registrationSubDistrict?.name ?? null,
      lastUpdatedAt: item.lastUpdatedAt,
      lastUpdateFullName: item.lastUpdateFullName,
    }));
    return new HttpSuccess(_record);
  }

  /**
   *
   * @summary ประวัติแก้ไขที่อยู่
   *
   */
  @Get("history/{profileId}")
  public async getProfileAddressHistory(
    @Path() profileId: string,
    @Request() req: RequestWithUser,
  ) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_TEMP");
    if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP");
    const record = await this.profileAddressHistoryRepo.find({
      where: { profileEmployeeId: profileId },
      relations: [
        "registrationProvince",
        "registrationDistrict",
        "registrationSubDistrict",
        "currentProvince",
        "currentDistrict",
        "currentSubDistrict",
      ],
      order: { createdAt: "DESC" },
    });
    const _record = record.map((item) => ({
      id: item.id,
      currentAddress: item.currentAddress,
      registrationAddress: item.registrationAddress,
      currentZipCode: item.currentZipCode,
      registrationZipCode: item.registrationZipCode,
      currentProvince: item.currentProvince?.name ?? null,
      registrationProvince: item.registrationProvince?.name ?? null,
      currentDistrict: item.currentDistrict?.name ?? null,
      registrationDistrict: item.registrationDistrict?.name ?? null,
      currentSubDistrict: item.currentSubDistrict?.name ?? null,
      registrationSubDistrict: item.registrationSubDistrict?.name ?? null,
      lastUpdatedAt: item.lastUpdatedAt,
      lastUpdateFullName: item.lastUpdateFullName,
    }));
    return new HttpSuccess(_record);
  }

  /**
   *
   * @summary แก้ไขที่อยู่
   *
   */
  @Patch("{profileId}")
  public async editProfileAddress(
    @Body() body: UpdateProfileAddressEmployee,
    @Request() req: RequestWithUser,
    @Path() profileId: string,
  ) {
    await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP");
    const record = await this.profileEmployeeRepo.findOneBy({ id: profileId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const before = structuredClone(record);
    // const before_null = null;
    const history = new ProfileAddressHistory();

    Object.assign(record, body);
    Object.assign(history, { ...record, id: undefined });

    history.profileEmployeeId = profileId;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();
    history.lastUpdateUserId = req.user.sub;
    history.lastUpdateFullName = req.user.name;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.profileEmployeeRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.profileAddressHistoryRepo.save(history, { data: req }),
      // setLogDataDiff(req, { before: before_null, after: history }),
    ]);

    return new HttpSuccess();
  }
}
